Skip to content
Advertisement

How to combine two lists from the same relation in Java-8

I have below entities Manager and Colleague

Manager Entity

@Entity
@Table(name = "Manager")
@Data
public class Manager implements java.io.Serializable {

    @Id
    @Column(name = "id")
    private Long id;
    
    @Column(name = "name")
    private String name;

    @OneToMany
    @JoinColumn(name = "id")
    private List<Colleague> colleagues;
}

Colleague Entity

@Entity
@Table(name = "Colleague")
@Data
public class Colleague implements java.io.Serializable {

    @Id
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;
}

Above relation can be represented in JSON as

[
  {
    "id": "101",
    "name": "manager1",
    "colleagues": [
      {
        "id": "101",
        "name": "colleague1"
      },
      {
        "id": "101",
        "name": "colleague2"
      }
    ]
  },
  {
    "id": "101",
    "name": "manager2",
    "colleagues": [
      {
        "id": "101",
        "name": "colleague3"
      },
      {
        "id": "101",
        "name": "colleague4"
      }
    ]
  }
]

I am retrieving the result on managerReposiotry.findAll() as

List<Manager> managerList = managerReposiotry.findAll();

I want to create a super list of all names from Manager and Colleague

What I am currently doing is

List<String> names = new ArrayList<>();
managerList.stream()
           .forEach(manager -> {
                 List<String> nameList = 
                     manager.getColleagues().stream()
                                            .map(colleague -> colleague.getName())
                                            .collect(Collectors.toList());
                 names.addAll(nameList);
              }
           );

Is there any other way in Java-8 to improve the above code?

Thank you !!

Advertisement

Answer

You can use flatMap to flatten all Colleague of Manager then map Colleague name only and collect as list.

List<String> names =
        managerList.stream()                                   // ...Stream<Manager>
                   .flatMap(m -> m.getColleagues().stream())   // ...Stream<Colleague>
                   .map(c-> c.getName())                       // ...Stream<String>
                   .collect(Collectors.toList());

But the better way is directly fetched from the database if all colleagues have manager.

@Query("select c.name from Colleagues c")
List<String> findAllColleagueName();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement