※ 引述《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