【发布时间】:2020-03-19 11:13:53
【问题描述】:
我有这个 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;
...
}
还有这个教授类:(应该是一个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排序,与流。
因此,我想要按评分(使用 favoritesByRating)收集所有最喜欢的 CasaDeBurrito 餐厅。
例如:
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;
}
【问题讨论】:
-
你想要什么输出?好像你想要
flatMap... -
您可能在寻找 flatMap:docs.oracle.com/javase/8/docs/api/java/util/stream/…
-
能否请您给我们看一下您的模型的短板,这样我们无法理解您想要达到的效果
-
forEach是void终端操作。它不会按要求返回结果。 -
注意flatMap功能,这里有一个很好的例子mkyong.com/java8/java-8-flatmap-example
标签: java collections java-stream flatten