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

时间:2016-06-30 12:25:09

标签: java collections lambda java-stream

拥有此代码:

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​​错了吗?请帮我改进我的代码!

1 个答案:

答案 0 :(得分:4)

$ mkdir -p .source/wall/model/bottom.png
$ make -f test.mk wall/red
running: wall/red/top.png
running: wall/red/bottom.png
running: wall/red

这与非流代码完全相同。