用Java中的流API调用替换for

编程入门 行业动态 更新时间:2024-10-24 22:18:22
Java中的流API调用替换for-each循环(Replacing for-each loop with stream API call in Java)

有这个代码:

public Map<Job, Collection<JobTransform>> getPartitioning() { Map<Job, Collection<JobTransform>> partitioning = new IdentityHashMap<>(); for (JobTransform jobTransform : content) { Job job = jobTransform.getJob(); Collection<JobTransform> collection = partitioning.get(job); if (collection == null) { collection = new LinkedList<>(); partitioning.put(job, collection); } collection.add(jobTransform); } return partitioning; }

'content'是实现此方法的类的构造函数参数,如何使用Java中的Stream API将for-each循环转换为代码? 现在我只有

content.stream().map(JobTransform::getJob)

而且我不知道如何进一步使用每项工作。 我使用API​​错了吗? 请帮我改进我的代码!

Having this code:

public Map<Job, Collection<JobTransform>> getPartitioning() { Map<Job, Collection<JobTransform>> partitioning = new IdentityHashMap<>(); for (JobTransform jobTransform : content) { Job job = jobTransform.getJob(); Collection<JobTransform> collection = partitioning.get(job); if (collection == null) { collection = new LinkedList<>(); partitioning.put(job, collection); } collection.add(jobTransform); } return partitioning; }

and 'content' being a constructor parameter for the class this method is implemented in, how can I convert the for-each loop into code using Stream API in Java? For now I have only

content.stream().map(JobTransform::getJob)

and I don't know how can I use each job further. Do I use the API wrong? Please help me to improve my code!

最满意答案

content.stream().collect(Collectors.groupingBy(JobTransform::getJob, IdentityHashMap::new, Collectors.toCollection(LinkedList::new)));

这将与非流代码完全相同。

content.stream().collect(Collectors.groupingBy(JobTransform::getJob, IdentityHashMap::new, Collectors.toCollection(LinkedList::new)));

This will do exactly the same thing as your non-stream code.

更多推荐

本文发布于:2023-08-02 01:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1368001.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!