Java流压缩两个列表 [英] Java streams zip two lists
问题描述
我有一个HashSet of Persons.一个人的名字,姓氏和年龄如下:Person("Hans","Man",36)
I have a HashSet of Persons. A person has a firstName, lastName and age like: Person("Hans", "Man", 36)
我的任务是获取17岁以上的人的列表,并按年龄对他们进行排序,然后将firstName与lastName合并 像:["Hans Man",另一个名字",另一个名字"]
My task is to get a list of the persons who are older than 17, sort them by age and concat the firstName with the lastName like: ["Hans Man","another name", "another name"]
我只允许导入:
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
我的想法是先对它们进行排序,将名称映射到单独的流中并压缩它们,但这是行不通的.
My idea was to sort them first, map the names in separate Streams and to zip them, but it doesn't work.
public static void getNamesOfAdultsSortedByAge(Stream<Person> stream){
Stream<Person> result = stream;
Stream<Person> result1 = result.filter(p -> p.getAge() >= 18)
.sorted((x, y) -> Integer.compare(x.getAge(),y.getAge()));
Stream<String> firstName = result1.map(Person::getFirstName);
Stream<String> lastName = result1.map(Person::getLastName);
Stream<String> result3 = concat(firstName, lastName);
List<String> result4 = result3.collect(Collectors.toList());
System.out.println(result4);
}
先谢谢您
推荐答案
您可以使用:
public static void getNamesOfAdultsSortedByAge(Stream<Person> stream) {
List<String> sorted = stream.filter(p -> p.getAge() >= 18)
.sorted((x, y) -> Integer.compare(x.getAge(),y.getAge()))
.map(e -> e.getFirstName() + " " + e.getLastName())
.collect(Collectors.toList());
System.out.println(sorted);
}
在这里,我们只是通过串联名字和姓氏来map
排序的流,然后使用.collect()
终端操作将其收集到列表中.
Here we just map
the sorted stream by concatenating the first name and then the last name, after which we use the .collect()
terminal operation to collect it to a list.
这篇关于Java流压缩两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!