简体   繁体   English

用Java中的流API调用替换for-each循环

[英]Replacing for-each loop with stream API call in Java

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? 并且“内容”是实现此方法的类的构造函数参数,如何使用Java中的Stream API将for-each循环转换为代码? 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? 我使用的API是否错误? Please help me to improve my code! 请帮助我改善代码!

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

这将与您的非流代码完全一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM