问题和练习的答案:综合操作

Questions

double average = roster
    .stream()
    .filter(p -> p.getGender() == Person.Sex.MALE)
    .mapToInt(Person::getAge)
    .average()
    .getAsDouble();

答:中级:filtermapToInt
1 号航站楼_
终端操作average返回OptionalDouble。然后,在该返回的对象上调用getAsDouble方法。最好向API Specification咨询有关操作是中间操作还是终端操作的信息。

Example:

List<String> namesOfMaleMembersCollect = roster
    .stream()
    .filter(p -> p.getGender() == Person.Sex.MALE)
    .map(p -> p.getName())
    .collect(Collectors.toList());

Exercises

for (Person p : roster) {
    if (p.getGender() == Person.Sex.MALE) {
        System.out.println(p.getName());
    }
}

Answer:

roster
    .stream()
    .filter(e -> e.getGender() == Person.Sex.MALE)
    .forEach(e -> System.out.println(e.getName());
List<Album> favs = new ArrayList<>();
for (Album a : albums) {
    boolean hasFavorite = false;
    for (Track t : a.tracks) {
        if (t.rating >= 4) {
            hasFavorite = true;
            break;
        }
    }
    if (hasFavorite)
        favs.add(a);
}
Collections.sort(favs, new Comparator<Album>() {
                           public int compare(Album a1, Album a2) {
                               return a1.name.compareTo(a2.name);
                           }});

Answer:

List<Album> sortedFavs =
  albums.stream()
        .filter(a -> a.tracks.anyMatch(t -> (t.rating >= 4)))
        .sorted(Comparator.comparing(a -> a.name))
        .collect(Collectors.toList());

在这里,我们使用流操作简化了三个主要步骤中的每个步骤-识别专辑中的任何曲目是否具有至少 4(anyMatch)的评分,排序以及将符合我们条件的专辑收集为ListComparator.comparing()方法采用提取Comparable排序键并返回与该键进行比较的Comparator的函数。

首页