以下是代码:
String[] array1 ={"ab", "cf", "cg", "ab", "nf", "ab", "nf", "cf", "cf", "ab"};
String[] array2 = new String[3];
for(int i=0; i<3; i++) {
System.out.println(array2[i]);
}
答案 0 :(得分:2)
试试这个。
String[] array1 ={"ab", "cf", "cg", "ab", "nf", "ab", "nf", "cf", "cf", "ab"};
String[] array2 = Stream.of(array1)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.sorted(Comparator.comparing(e -> -e.getValue()))
.limit(3)
.map(Entry::getKey)
.toArray(String[]::new);
System.out.println(Arrays.toString(array2));
结果:
[ab, cf, nf]
答案 1 :(得分:0)
将流收集到地图中,您可以在其中查看出现的内容......
final Map<String, Long> occurrences = listOfStrings.stream().collect(Collectors.groupingBy(x -> x, Collectors.counting()));
System.out.println(occurrences);