Created
November 1, 2019 08:59
-
-
Save zeraf29/7f6a60b3f165795deb981e2ad122da0b to your computer and use it in GitHub Desktop.
Find max number of elements in list using stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// find max number of elements in list like below example | |
// ex) in beloew list, elements '3' has max number of elements(max count how many exist in list) | |
// List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5, 4, 3, 2, 1, 3, 4); | |
// elements '3' and '4' have frequency 4 in this list. | |
// but '3' is smaller than '4', So elements '3' is max number of elements. | |
// Complete the migratoryBirds function below. | |
static int migratoryBirds(List<Integer> arr) { | |
//return arr.stream().filter(i -> Collections.frequency(arr, i) > 1).max(Integer::compare).get(); | |
// get Frequency each elements -> return Map | |
Map<Integer, Long> cntList = arr.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); | |
// compare using reduce, What has most bigger frequency(getValue) and smaller self than others(getKey) | |
return cntList.entrySet().stream().reduce((x,y)-> (x.getValue()>=y.getValue())?(x.getKey()<=y.getKey()?x:y):y).get().getKey(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment