有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从对象流中统一对象集合

我有一个卡萨迪玉米煎饼课:

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;
...
}

这个教授班:(应该是一个s)

public class ProfessorImpl implements OOP.Provided.Profesor {

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

    private Comparator<CasaDeBurrito> ratingComparator = (CasaDeBurrito c1, CasaDeBurrito c2) ->
    {
        if (c1.averageRating() == c2.averageRating()) {
            if (c1.distance() == c2.distance()) {
                return Integer.compare(c1.getId(), c2.getId());
            }
            return Integer.compare(c1.distance(), c2.distance());
        }
        return Double.compare(c2.averageRating(), c1.averageRating());
    };

    private Predicate<CasaDeBurrito> isAvgRatingAbove(int rLimit) {
        return c -> c.averageRating() >= rLimit;
    };

    public Collection<CasaDeBurrito> 
    filterAndSortFavorites(Comparator<CasaDeBurrito> comp, Predicate<CasaDeBurrito> p) {
            return favorites.stream().filter(p).sorted(comp).collect(Collectors.toList());
    }

    public Collection<CasaDeBurrito> favoritesByRating(int rLimit) {
            return filterAndSortFavorites(ratingComparator, isAvgRatingAbove(rLimit));
    }
}

我想实现一个函数,它获取一个Profesor prof,并将所有prof的朋友的所有favorites集合统一起来,按ID排序,带有流。 因此,我想收集所有最受欢迎的CasaDeBurrito餐馆的评级(带有favoritesByRating)

例如:

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;
}

共 (1) 个答案

  1. # 1 楼答案

    所以我不知道如何正确提问,但我设法将评论和答案与我需要的联系起来。 我按ID对朋友进行排序,并在他的评论中创建了一个集合流@Alex Faster sharehere,并按照上面的建议将该流展平

    return p.getFriends().stream()  //Stream<Profesor>
                    .sorted(Comparator.comparingInt(Profesor::getId)) //Stream<Profesor>
                    .map(P->P.favoritesByDist(0)) //Stream<Collection<CasaDeBurrito>>
                    .flatMap(Collection::stream) //Stream<CasaDeBurrito>
                    .distinct()
                    .collect(Collectors.toList()); //List<CasaDeBurrito>
    

    我将再次编辑我的问题,使其更加清晰