aboutsummaryrefslogtreecommitdiff
path: root/challenge-074/shawn-wagner/java/ch1.java
blob: 7d14236d22fdbdb0ac0c12681670e40a382f8f96 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Use streams to calculate the count of distinct elements in an array and
// filter out just the first one above the cutoff.

// I'm particularly proud of this one.

import java.util.*;
import java.util.stream.*;
import java.util.function.Function;

class ch1 {
    private static void task1(int[] a) {
        int cutoff = (int)Math.floor(a.length / 2.0);
        int over_cutoff =
            Arrays.stream(a).boxed()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .entrySet().stream()
            .filter(entry -> entry.getValue() > cutoff)
            .findFirst().map(entry -> entry.getKey()).orElse(-1);
        System.out.println(over_cutoff);
    }

    public static void main(String[] args) {
        task1(new int[] {1, 2, 2, 3, 2, 4, 2});
        task1(new int[] {1, 3, 1, 2, 4, 5});
    }
}