stream.forEach内部的stream.concat

问题描述 投票:0回答:1

我是Java的新手,我不知道如何连接嵌套流。我有这个CasaDeBurrito课:

public class CasaDeBurritoImpl implements OOP.Provided.CasaDeBurrito {

    private Integer id;
    private String name;
    private Integer dist;
    private Set<String> menu;
    private Map<Integer, Integer> ratings;
...
}

和此教授类:(应该是一个)

public class ProfessorImpl implements OOP.Provided.Profesor {

    private Integer id;
    private String name;
    private List<CasaDeBurrito> favorites;
    private Set<Profesor> friends;
...
}

现在,我想编写一个函数,该函数可以流式传输所有教授的朋友,并且forEach每个朋友都可以流式传输所有喜爱的CasaDeBurrito餐厅(与func favoritesByRating(0))并将其全部合并以进行更多的中间操作。例如:

public Collection<CasaDeBurrito> favoritesByRating(Profesor p) {

    Stream ret = p.getFriends().stream()
               .<*some Intermediate Operations*>.
               .forEach(y->y.concat(y.favoritesByRating(0))
               .<*some Intermediate Operations*>.
               .collect(toList());
    return ret;
}

favoritesByRating签名:

Collection<CasaDeBurrito> favoritesByRating(int rLimit);

正如我在开始时提到的,我是Java的新手,对流的工作原理还不够了解,所以我不知道是否可行。

作为输出,我希望按名称排序的所有朋友的CasaDeBurrito收藏夹的集合。

java collections java-stream concat
1个回答
0
投票

[您想要a collection of all CasaDeBurrito favorites by friends sorted by name,所以我想说Map<String, List<CasaDeBurrito>>将是您所需要的,每个键都是朋友的名字,并且值是他喜欢使用CasaDeBurrito方法使用的favoritesByRating的列表,全部排序按名称(使用TreeMap

public Map<String, List<CasaDeBurrito>> favoritesByRating(Profesor p) {
    return p.getFriends().stream()
            .collect(toMap(Profesor::getName, prof -> prof.favoritesByRating(0), (i, j) -> i, TreeMap::new));
}

如果您只想获得朋友喜欢的CasaDeBurrito列表,请使用flatMap

public List<CasaDeBurrito> favoritesByRating(Profesor p) {
    return p.getFriends().stream()
            .flatMap(prof -> prof.favoritesByRating(0).stream())
            .collect(toList());
}
© www.soinside.com 2019 - 2024. All rights reserved.