java 流压缩,Java流压缩两个列表

该博客介绍如何使用Java Stream API过滤出年龄大于17岁的人员,按年龄排序,并将他们的名字首尾相连。提供的代码示例展示了如何通过filter、sorted、map和collect操作实现这一目标。
摘要由CSDN通过智能技术生成

I have a HashSet of Persons. A person has a firstName, lastName and age like: Person("Hans", "Man", 36)

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"]

Im just allowed to import:

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 stream){

Stream result = stream;

Stream result1 = result.filter(p -> p.getAge() >= 18)

.sorted((x, y) -> Integer.compare(x.getAge(),y.getAge()));

Stream firstName = result1.map(Person::getFirstName);

Stream lastName = result1.map(Person::getLastName);

Stream result3 = concat(firstName, lastName);

List result4 = result3.collect(Collectors.toList());

System.out.println(result4);

}

thank you in advance

解决方案

You could do so using :

public static void getNamesOfAdultsSortedByAge(Stream stream) {

List 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);

}

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值