Re: [問題] 字串計數

看板java作者 (畢業了..@@")時間9年前 (2014/10/13 10:47), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串7/8 (看更多)
※ 引述《smith80512 (Henry)》之銘言: : 想請問版上前輩們 : 文章內容已經分割成字串陣列 : 如何計數該陣列重複的字串? : 並指顯示最多出現和次多出現的字串 : 以及利用ArrayList回傳? 剛好WordCount的問題很適合用新的Stream API來做 這邊做個示範 public class WordCount { public static void main(String[] args) { List<String> words = Arrays.asList( "hello", "hello", "word", "word", "count", "a", "b", "c", "d", "a", "b", "c", "b"); // Group by word and aggregate by count // key = word, value = count Map<String, Long> wordCount = words .stream() .collect(Collectors.groupingBy(word -> word, Collectors.counting())); wordCount.forEach((k, v) -> System.out.println(k + " -> " + v)); // Sort the entries by value in descending order List<String> sortedWords = wordCount.entrySet() .stream() .sorted((e1, e2) -> (int) -(e1.getValue() - e2.getValue())) .map(e -> e.getKey()) .collect(Collectors.toList()); // Dump the result sortedWords.forEach((word) -> System.out.println(word)); } } ///output 長這樣 a -> 2 b -> 3 c -> 2 d -> 1 count -> 1 hello -> 2 word -> 2 b a c hello word d count -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.163.46.230 ※ 文章網址: http://www.ptt.cc/bbs/java/M.1413168477.A.CCF.html
文章代碼(AID): #1KEprTpF (java)
討論串 (同標題文章)
文章代碼(AID): #1KEprTpF (java)