使用Java8流对对象属性进行迭代

使用Java8流对对象属性进行迭代,java,java-8,java-stream,Java,Java 8,Java Stream,我有一个Publication对象的列表,我想为地图的Publication中的每个对象获取相应的PublicationKeyword,格式为:map,其中外部地图的键是列表中Publication的id,值是地图,其中键是一个关键字对象,整数是它的频率 目前,我是这样做的: public Map<Integer, Map<Keyword, Integer>> getFrequencies(List<Publication> publications) {

我有一个
Publication
对象的
列表
,我想为地图的
Publication
中的每个对象获取相应的
PublicationKeyword
,格式为:
map
,其中外部地图的键是列表中
Publication
的id,值是地图,其中键是一个
关键字
对象,
整数
是它的频率

目前,我是这样做的:

public Map<Integer, Map<Keyword, Integer>> getFrequencies(List<Publication> publications) {
        Map<Integer, Map<Keyword, Integer>> resultSet = new HashMap<>();
        for (Publication publication : publications) {
            Map<Keyword, Integer> frequencyMappings = new HashMap<>();
            for (PublicationKeyword pubKeyword : publication.getPublicationKeyword()) {
                frequencyMappings.put(pubKeyword.getKeyword(), pubKeyword.getConceptFrequency());
            }
            resultSet.put(publication.getIdPaper(), frequencyMappings);
        }
        return resultSet;
    }
公共地图获取频率(列出出版物){
Map resultSet=new HashMap();
用于(出版物:出版物){
Map frequencyMappings=new HashMap();
对于(PublicationKeyword pubKeyword:publication.getPublicationKeyword()){
frequencyMappings.put(pubKeyword.getKeyword(),pubKeyword.getConceptFrequency());
}
resultSet.put(publication.getIdPaper(),frequencyMappings);
}
返回结果集;
}
但是,问题是我想使用Java8流来实现这一点。有可能吗?如果是,正确的方法是什么?让我困惑的是:嵌套的for循环和for内部变量的声明

这应该可以做到:

return publications.stream()
    .collect(Collectors.toMap(
        Publication::getIdPaper,
        publication -> publication.getPublicationKeyword()
            .stream()
            .collect(Collectors.toMap(
                PublicationKeyword::getKeyword,
                PublicationKeyword::getConceptFrequency))));
这应该做到:

return publications.stream()
    .collect(Collectors.toMap(
        Publication::getIdPaper,
        publication -> publication.getPublicationKeyword()
            .stream()
            .collect(Collectors.toMap(
                PublicationKeyword::getKeyword,
                PublicationKeyword::getConceptFrequency))));

看起来很棒。简短的问题,哪一个更有效:使用streams还是经典的Java 7 way?定义“高效”。@Cap作为一般规则,streams的效率将低于简单的循环,但您通常应该关注可读性,并且仅在有明显需要时进行优化。上述情况的例外是并行流,它可能比顺序操作更有效。但再一次,千万不要假设。@shmosel哦,我显然是想错了。我原以为simple
stream
也在假设并行性(因此它分布在多核上),但现在我意识到我需要并行流来代替它。@Thorbjørnravandersen,“高效”同时使用多核(多CPU)。看起来很棒。简短的问题,哪一个更有效:使用streams还是经典的Java 7 way?定义“高效”。@Cap作为一般规则,streams的效率将低于简单的循环,但您通常应该关注可读性,并且仅在有明显需要时进行优化。上述情况的例外是并行流,它可能比顺序操作更有效。但再一次,千万不要假设。@shmosel哦,我显然是想错了。我原以为simple
stream
也在假设并行性(因此它分布在多核上),但现在我意识到我需要并行流来代替它。@Thorbjørnravandersen,“高效”地同时使用多核(多CPU)。