Re: [問題] 字串計數

作者: popcorny (畢業了..@@")   2014-10-13 10:47:55
※ 引述《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

Links booklink

Contact Us: admin [ a t ] ucptt.com