Java 8 streams, grouping by transformed stream object

Following example demonstrates, how to use Java streams to group an object based on its property and transforming the object to some other Class before they are collected in a list.

In the following example, we create a list of objects of Class A and stream the list to produce a map based on a property of Class A but containing a list of objects of Class B.

 public class A {  
      public A(String a) {  
           super();  
           this.a = a;  
      }  
      private String a;  
      public String getA() {  
           return a;  
      }  
      public void setA(String a) {  
           this.a = a;  
      }  
 }  

 public class B {  
      public B(String a) {  
           super();  
           this.a = a;  
      }  
      private String a;  
      public String getA() {  
           return a;  
      }  
      public void setA(String a) {  
           this.a = a;  
      }  
 }  

 public class Main {  
      public static void main(String a[]) {  
           A a1 = new A("a");  
           A a2 = new A("a");  
           A a3 = new A("b");  
           A a4 = new A("b");  
           A a5 = new A("b");  
           A a6 = new A("c");  
           List<A> aList = Arrays.asList(a1,a2,a3,a4,a5,a6);  
           Map<String, List<B>> bMap ;  
           bMap = aList.stream().collect(Collectors.groupingBy(A::getA,Collectors.mapping(k -> getB(k), Collectors.toList())));  
           System.out.println(bMap);  
      }  
      private static B getB(A a) {  
           return new B(a.getA());  
      }  
 }  

Output : {a=[trials.B@6d03e736, trials.B@568db2f2], b=[trials.B@378bf509, trials.B@5fd0d5ae, trials.B@2d98a335], c=[trials.B@16b98e56]}

Comments

Popular posts from this blog

Caused by: java.sql.SQLTimeoutException: ORA-01013: user requested cancel of current operation

HashiCorp Vault Integration with Ansible Etower using approle

utility to extract date from text with java