如何将一个集合中的值添加到另一个集合中?

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

How to add value to set from another set?

问题

我有一个Set<RollingField> rollingFields,我需要将字段添加到另一个集合中:Set<String>

现在我有如下代码:

Set<String> fieldNames = new HashSet<>();
rollingFields.forEach(e -> fieldNames.add(e.getMeta().getName()));

我该如何将它改成一行,类似于(我的方法不起作用):

Set<String> fieldNames1 = rollingFields.stream().map(rf -> rf.getMeta().getName());
英文:

I have Set&lt;RollingField&gt; rollingFields and I need to add field to another set: Set&lt;String&gt;

Now I have code like:

Set&lt;String&gt; fieldNames = new HashSet&lt;&gt;();
rollingFields.forEach(e -&gt; fieldNames.add(e.getMeta().getName()));

How can I change it to one line like (my way is not working)?:

Set&lt;String&gt; fieldNames1 = rollingFields.stream().map(rf -&gt; rf.getMeta().getName());

答案1

得分: 1

你已经快要完成了。你只需要将流的结果收集到一个集合中:

rollingFields.stream().map(rf -> rf.getMeta().getName()).collect(Collectors.toSet());
英文:

You're already almost done. You just need to collect the stream results to a set:

rollingFields.stream().map(rf -&gt; rf.getMeta().getName()).collect(Collectors.toSet());

答案2

得分: 1

你的想法是对的,你只需要将你拥有的流收集到一个集合中:

Set<String> fieldNames1 =
    rollingFields.stream().map(rf -> rf.getMeta().getName()).collect(Collectors.toSet());
英文:

You have the right idea, you just need to collect the stream you have to a set:

Set&lt;String&gt; fieldNames1 =
    rollingFields.stream().map(rf -&gt; rf.getMeta().getName()).collect(Collectors.toSet());

huangapple
  • 本文由 发表于 2020年4月10日 20:59:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/61140765.html
匿名

发表评论

匿名网友

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

确定