英文:
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<RollingField> rollingFields
and I need to add field to another set: Set<String>
Now I have code like:
Set<String> fieldNames = new HashSet<>();
rollingFields.forEach(e -> fieldNames.add(e.getMeta().getName()));
How can I change it to one line like (my way is not working)?:
Set<String> fieldNames1 = rollingFields.stream().map(rf -> 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 -> 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<String> fieldNames1 =
rollingFields.stream().map(rf -> rf.getMeta().getName()).collect(Collectors.toSet());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论