public class Main {
public static void main(String[] args) {
int[] a = {1,3,4,3,4,3,2,3,3,3,3,3};
List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
Map<Integer, Long> map = list.parallelStream()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println("Map => " + map);
//{1=1, 2=1, 3=8, 4=2}
map.entrySet()
.stream()
.max(Comparator.comparing(Entry::getValue))//compare the values and get the maximum value
.map(Entry::getKey)// get the key appearing maximum number of times
.ifPresentOrElse(System.out::println,() -> new RuntimeException("no such thing"));
/*
* OUTPUT : Map => {1=1, 2=1, 3=8, 4=2}
* 3
*/
// or in this way
System.out.println(".............");
Integer maxAppearedElement = map.entrySet()
.parallelStream()
.max(Comparator.comparing(Entry::getValue))
.map(Entry::getKey)
.get();
System.out.println(maxAppearedElement);
}
}
16条答案
按热度按时间wj8zmpe116#
Map中的多数元素/最大元素: