JAVA8 Stream 多个对象List中的指定字段抽取到一个List中

定义一个Person类

public class Person {
 
    private Integer id;
    private String name;
    private String address;
    
	// 省略get和set和构造方法
}

方式一

List<Person> person1List= Arrays.asList(new Person(1, "张三"), new Person(2, "李四"));
List<Person> person2List= Arrays.asList(new Person(1, "王五"), new Person(3, "赵六"));

// 将List1和List2分别获取出id之后合并为一个stream流,然后收集为List
List<Integer> personIdList = Stream.concat(
	person1List.stream().map(Room::getId), 
	person2List.stream().map(Room::getId)
).collect(Collectors.toList());

方式二

List<Person> person1List= Arrays.asList(new Person(1, "张三"), new Person(2, "李四"));
List<Person> person2List= Arrays.asList(new Person(1, "王五"), new Person(3, "赵六"));

// List1和List2先合并为一个Stream流之后,然后获取id,最后收集为List
List<Integer> personIdList =  Stream.of(person1List, person2List)
							  .flatMap(List::stream)
							  .map(Person::getId)
							  .collect(Collectors.toList());

你可能感兴趣的:(#,Stream流,Java,list,java)