Share

Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#Collectors.groupingBy' - 3 code snippet(s) found

 Sample 1. Group Elements by even or Odd using Lambda Expressions

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and Collector to Group by Even and Odd

System.out.println(intSet.stream().collect(Collectors.groupingBy(p->((Integer)p)%2)));  Prints {0=[2, 4], 1=[1, 3]}

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.groupingBy


 Sample 2. Sum all collection elements using Lambda Expressions

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and collectors to sum all elements.

System.out.println(intSet.stream().collect(Collectors.summingInt(p->(Integer)p)));

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.groupingBy


 Sample 3. Averaging Group By using Java 8

<Collection_Reference>.stream().collect(Collectors.groupingBy(<Class_Name>::<Method_to_get_group_by_element>,
               Collectors.averagingDouble(<Class_Name>::<Method_to_get_element_to_perform_averaging_on>)));

Example -

Get Dept and it's average Salary

list..stream().collect(Collectors.groupingBy(Employee::getDept,
               Collectors.averagingDouble(Employee::getSalary)));

   Like      Feedback     java 8



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner



comments powered by Disqus