In statistics, this is called the "mode". A vanilla Java 8 solution looks like this:
Stream.of(1, 3, 4, 3, 4, 3, 2, 3, 3, 3, 3, 3)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.ifPresent(System.out::println);
Which yields:
3=8
jOOλ is a library that supports mode()
on streams. The following program:
System.out.println(
Seq.of(1, 3, 4, 3, 4, 3, 2, 3, 3, 3, 3, 3)
.mode()
);
Yields:
Optional[3]
For simplicity's sake, I omitted using BigDecimal
. The solution would be the same, though.
(disclaimer: I work for the company behind jOOλ)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…