Java streams zip two lists

oddi :

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

thank you in advance

Nicholas K :

You could do so using :

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

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113687&siteId=1