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

Viewed 30

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}

2 Answers

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]

From your question, I only able to understand that you want to convert your Collection of Class A to make Collection of String (i.e. value should be like this a.title +" "+a.classb.name)

What you are looking for as follows

list.stream()
    .map(a-> String.join(" ", a.title, a.classb.name))
    .collect(Collectors.toList())
    .forEach(System.out::println);
Related