Search code examples
java-8stream

get list of String from array of objects with concat in java 8


I have 2 java Classes :-

class A {
 String title;
 B classb;
}

class B {
 String name;
}

Now I have List of class A and the result which I am looking for :-

List of {a.title +" "+a.classb.name}


Solution

  • Using java 8 stream API:

    A.java

    public class A {
      private String title;
      private B classB;
    
      public A(String title, B classB) {
        this.title = title;
        this.classB = classB;
      }
    
      public String getTitle() {
        return title;
      }
    
      public void setTitle(String title) {
        this.title = title;
      }
    
      public B getClassB() {
        return classB;
      }
    
      public void setClassB(B classB) {
        this.classB = classB;
      }
    
      @Override
      public String toString() {
        return "A{" +
            "title='" + title + '\'' +
            ", classB=" + classB +
            '}';
      }
    

    B.java

    public class B {
      private String name;
    
      public B(String name) {
        this.name = name;
      }
    
      public String getName() {
        return name;
      }
    
      public void setName(String name) {
        this.name = name;
      }
    
      @Override
      public String toString() {
        return "B{" +
            "name='" + name + '\'' +
            '}';
      }
    

    Test.java

    public class Test {
      public static void main(String[] args) {
        A a1 = new A("titleA1",new B("B1"));
        A a2 = new A("titleA2",new B("B2"));
        A a3 = new A("titleA3",new B("B3"));
        A a4 = new A("titleA4",new B("B4"));
    
        List<A> list = Arrays.asList(a1,a2,a3,a4);
    
        List<String> updatedList = list.stream().map(x -> x.getTitle() + " " + x.getClassB().getName()).collect(Collectors.toList());
    
        System.out.println(updatedList);
      }
    }
    

    Output::

    [titleA1 B1, titleA2 B2, titleA3 B3, titleA4 B4]