我正在编写代码以按年龄对人员列表进行排序,并以年龄最大的人为前缀并打印出来
定义的对象列表:
Person person1 = new Person(40,"John", "Smith");
Person person2 = new Person(45,"Mike", "Well");
Person person3 = new Person(68,"Bob", "Parks");
Person person4 = new Person(49,"Leon", "Foo");
Person person5 = new Person(30,"Christian", "Markus");
List<Person> personList = new ArrayList<>();
personList.add(person1);
personList.add(person2);
personList.add(person3);
personList.add(person4);
personList.add(person5);
我可以对其进行排序和添加前缀,但问题是要获取第一项并打印出来
List<Person> orderedPersonAge = personList
.stream()
.sorted(Comparator.comparing(Person::getAge).reversed())
.map(s-> new
Person(s.getAge(),"Super"+s.getName(),s.getSureName()))
.collect(Collectors.toList());
System.out.println(orderedPersonAge);
我尝试过使用findFirst()...
不同的方法是按年龄排序,取最早的,然后添加前缀...
答案 0 :(得分:1)
你可以做
Person orderedPersonAge = personList
.stream()
.sorted(Comparator.comparing(Person::getAge).reversed())
.map(s-> new Person(s.getAge(),"Super"+s.getName(),s.getSureName()))
.collect(Collectors.toList())
.get(0);
System.out.println(orderedPersonAge);
或
Person orderedPersonAge = personList
.stream()
.sorted(Comparator.comparing(Person::getAge).reversed())
.map(s-> new Person(s.getAge(),"Super"+s.getName(),s.getSureName()))
.findFirst()
.get();
System.out.println(orderedPersonAge);
答案 1 :(得分:0)
您可能正在寻找
personList.stream()
.max(Comparator.comparing(Person::getAge)) // solves for sort with reverse and find first
.map(s -> new Person(s.getAge(), "Super" + s.getName(), s.getSurname())) // map if present
.ifPresent(System.out::println); // print the mapped output if present