如何在Java 8中将来自同一关系的两个列表合并。

huangapple go评论125阅读模式
英文:

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

问题

我有以下实体 ManagerColleague

Manager 实体

@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
@Table(name = "Colleague")
@Data
public class Colleague implements java.io.Serializable {

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

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

上述关系可以表示为 JSON

[
  {
    "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"
      }
    ]
  }
]

我正在使用 managerReposiotry.findAll() 检索结果:

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

我想要创建一个包含来自 ManagerColleague 的所有姓名的超级列表。

我目前正在执行以下操作:

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);
              }
           );

Java 8 中是否有其他方法可以改进上述代码?

谢谢!

英文:

I have below entities Manager and Colleague

Manager Entity

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

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

	@OneToMany
	@JoinColumn(name = &quot;id&quot;)
	private List&lt;Colleague&gt; colleagues;
}

Colleague Entity

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

	@Id
	@Column(name = &quot;id&quot;)
	private Long id;

	@Column(name = &quot;name&quot;)
	private String name;
}

Above relation can be represented in JSON as

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

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

List&lt;Manager&gt; managerList = managerReposiotry.findAll();

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

What I am currently doing is

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

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

Thank you !!

答案1

得分: 3

你可以使用 flatMap 来展开所有 ManagerColleague,然后仅获取 Colleague 的姓名并以列表形式收集。

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

但更好的方式是,如果所有的同事都有经理,直接从数据库中获取。

@Query("select c.name from Colleagues c")
List<String> findAllColleagueName();
英文:

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

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

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

@Query(&quot;select c.name from Colleagues c&quot;)
List&lt;String&gt; findAllColleagueName();

huangapple
  • 本文由 发表于 2020年9月2日 13:13:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63699071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定