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.