×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Johny Done
Added: Dec 13, 2019 10:11 AM
Views: 4159
Tags: no tags
  1. import java.util.*;
  2. import java.util.stream.*;
  3. import java.util.function.*;
  4.  
  5. public class Test {
  6.     static class Obj{
  7.       String name;
  8.       int age;
  9.       char sex;
  10.  
  11.       public Obj(String name, int age, char sex){
  12.         this.name = name;
  13.         this.age = age;
  14.         this.sex = sex;
  15.       }
  16.  
  17.       public String toString(){
  18.         return (this.name + " " + this.age + " " + this.sex);
  19.       }
  20.     }
  21.  
  22.  
  23.     public static void main(String[] args){
  24.  
  25.       List<Obj> objs = new ArrayList<>();
  26.       objs.add(new Obj("Jan", 18, 'M'));
  27.       objs.add(new Obj("Piotr", 22, 'M'));
  28.       objs.add(new Obj("Lukasz", 31, 'M'));
  29.       objs.add(new Obj("Barbara", 40, 'K'));
  30.       objs.add(new Obj("Zaneta", 33, 'K'));
  31.       objs.add(new Obj("Magłgorzata", 24, 'K'));
  32.       objs.add(new Obj("Marcelina", 25, 'K'));
  33.  
  34.       objs.stream()
  35.           .filter(obj -> obj.age > 24)
  36.           .collect(Collectors.groupingBy(obj -> obj.sex))
  37.           .entrySet()
  38.           .forEach(System.out::println);
  39.     }
  40.  
  41.       objs.stream()
  42.           .collect(Collectors.groupingBy(obj -> obj.sex, Collectors.counting()))
  43.           .entrySet()
  44.           .forEach(System.out::println);
  45.     }
  46.  
  47.   }
  48.  
  49. // RESULT
  50. // K=[Barbara 40 K, Zaneta 33 K, Marcelina 25 K]
  51. // M=[Lukasz 31 M]
  52.  
  53. // K=4
  54. // M=3