I have two classes that are structured like this:
public class Company { private List<Person> person; ... public List<Person> getPerson() { return person; } ... } public class Person { private String tag; ... public String getTag() { return tag; } ... }
Basically the Company class has a List of Person objects, and each Person object can get a Tag value.
If I get the List of the Person objects, is there a way to use Stream from Java 8 to find the one Tag value that is the most common among all the Person objects (in case of a tie, maybe just a random of the most common)?
String mostCommonTag; if(!company.getPerson().isEmpty) { mostCommonTag = company.getPerson().stream() //How to do this in Stream? }
String mostCommonTag = getPerson().stream() // filter some person without a tag out .filter(it -> Objects.nonNull(it.getTag())) // summarize tags .collect(Collectors.groupingBy(Person::getTag, Collectors.counting())) // fetch the max entry .entrySet().stream().max(Map.Entry.comparingByValue()) // map to tag .map(Map.Entry::getKey).orElse(null);
AND the getTag
method appeared twice, you can simplify the code as further:
String mostCommonTag = getPerson().stream() // map person to tag & filter null tag out .map(Person::getTag).filter(Objects::nonNull) // summarize tags .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) // fetch the max entry .entrySet().stream().max(Map.Entry.comparingByValue()) // map to tag .map(Map.Entry::getKey).orElse(null);
You could collect the counts to a Map, then get the key with the highest value
List<String> foo = Arrays.asList("a","b","c","d","e","e","e","f","f","f","g"); Map<String, Long> f = foo .stream() .collect(Collectors.groupingBy(v -> v, Collectors.counting())); String maxOccurence = Collections.max(f.entrySet(), Comparator.comparing(Map.Entry::getValue)).getKey(); System.out.println(maxOccurence);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With