用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.
更多推荐
发布评论