gpt4 book ai didi

java - 如何获得数组中五个最少重复的元素

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:39:52 25 4
gpt4 key购买 nike

如果我有以下字符串数组。

String inStrings[] = {"A", "B", "C", "D", "E", "F", "G", "H", "A", "B", "C", "D", "E", "A", "B", "C", "D", "A", "B"};

然后这个数组被传递给一个方法,我不确定如何继续。

    static void getColdSearch(String[] inArray){



}

这个方法应该做的是获取数组,获取重复次数最少的字符串,然后在输出中打印出重复次数最少的五个字符串。重复的字符串不必彼此相邻,如果字符串少于五个,那么所有字符串都应该是输出的一部分。例如。如果 arraylist 看起来像上面的例子,输出应该是这样的。

F //(Occurs once)
G //(Occurs once)
H //(Occurs once)
E //(Occurs twice)
D //(if two different elements repeat the same number of times a random one of them should be printed)

我该怎么做?

最佳答案

尝试 java 8 特性

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class GroupingDemo {

public static void getColdSearch(String[] inArray) {
Map<String, Long> groupingByLetter = Arrays.stream(inArray)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

List<String> result = groupingByLetter.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.limit(5)
.map(Map.Entry::getKey)
.collect(Collectors.toList());

System.out.println(result);
}

public static void main(String[] args) {
String inStrings[] = {"A", "B", "C", "D", "E", "F", "G", "H", "A", "B", "C", "D", "E", "A", "B", "C", "D", "A", "B"};
getColdSearch(inStrings);
}
}

关于java - 如何获得数组中五个最少重复的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43745419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com