如何在String数组中选择三个最受欢迎的元素并将它们放在一个新的String数组中?

时间:2016-10-10 10:07:07

标签: java arrays

以下是代码:

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]);
}

2 个答案:

答案 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);