Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the most common attribute value from a List of objects using Stream

Tags:

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? } 
like image 389
000000000000000000000 Avatar asked Apr 25 '17 16:04

000000000000000000000


2 Answers

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); 
like image 177
holi-java Avatar answered Oct 18 '22 23:10

holi-java


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); 
like image 43
baao Avatar answered Oct 18 '22 23:10

baao