Java 如何使用流编译具有给定属性最大值的所有对象的列表?

Java 如何使用流编译具有给定属性最大值的所有对象的列表?,java,max,java-stream,filtering,Java,Max,Java Stream,Filtering,假设我有一个带有姓名和年龄属性的人的列表。如何使用流获取属性age值最大的人的所有实例 目前,我采用两步方法: 1) 寻找年龄的最大值 int maxAge = group .stream() .mapToInt(person -> person.getAge()) .max() .orElse(-1); 2) 创建具有该年龄的人的列表 List<Group> groupWithMaxAge = group

假设我有一个带有姓名和年龄属性的
人的列表。如何使用流获取属性age值最大的
人的所有实例

目前,我采用两步方法:

1) 寻找年龄的最大值

int maxAge = group
        .stream()
        .mapToInt(person -> person.getAge())
        .max()
        .orElse(-1);
2) 创建具有该年龄的
人的列表

List<Group> groupWithMaxAge = group
        .stream()
        .filter(person -> person.getAge() == maxAge)
        .collect(Collectors.toList());
List groupWithMaxAge=group
.stream()
.filter(person->person.getAge()==maxAge)
.collect(Collectors.toList());

不用担心,这很有效。然而,考虑到计算年龄是一个昂贵的函数的情况。在这种情况下,如果你能一次完成就好了,不是吗?

另一种选择是分组并选择最大键(
age
):

List peopleWithMaxAge=group.stream()
.collect(收集器.groupingBy(人员::getAge))
.entrySet()
.stream()
.sorted(Comparator.comparingInt(条目::getKey)
.reversed())
.findFirst()
.map(条目::getValue)
.orElse(新ArrayList())//如果原始列表为空,则为空列表

一种更干净的方法是:

List groupWithMaxAge=group.stream()//流

.collect(Collectors.groupingBy(Group::getAge))//Map您还可以将groupingBy与TreeMap一起用作映射工厂:

List<Group> list = people.stream()
            .collect(groupingBy(Group::getAge, TreeMap::new, toList()))
            .lastEntry()
            .getValue();
List List=people.stream()
.collect(groupingBy(Group::getAge,TreeMap::new,toList())
.lastEntry()
.getValue();

您认为这更有效吗?如果我没有弄错的话,您仍然在使用两个连续的流操作。@MWB,这取决于您的情况。如果我们可以合理地假设
age
是一个低基数字段,那么第二个流将处理更少的元素。有一件事是肯定的,那就是这比
组上的两个流要好。而且。。。如果
getAge
是一个昂贵的操作,那么它就不会被重做。这确实是一个更干净的方法+1.
List<Group> groupWithMaxAge = group.stream() // Stream<Group>
    .collect(Collectors.groupingBy(Group::getAge)) // Map<Integer, List<Group>
    .entrySet() // Set<Entry<Integer, List<Group>>>
    .stream().max(Comparator.comparingInt(Entry::getKey)) // Optional<Entry<Integer, List<Group>>>
    .map(Entry::getValue) // Optional<List<Person>>
    .orElse(new ArrayList<>());
List<Group> list = people.stream()
            .collect(groupingBy(Group::getAge, TreeMap::new, toList()))
            .lastEntry()
            .getValue();