简体   繁体   中英

Java 8 create map a list of a complex type to list of one of its fields

I have a list from some complex type and I want to figure a neat way to construct a list only from one of its fields using Java 8's streams. Let's take as an example:

public static class Test {
    public Test(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    private String name;
    // other fields
}

And imagine that I have a List<Test> l; . Now I want to create a new list that contains the values of name of all elements in l . One possible solution that I found is the following:

List<String> names = l.stream().map(u ->u.getName()).
    collect(Collectors.<String> toList());

But I was wondering if there is a better way to do this - map a list of a given type to another list of different type.

Using method references is shorter :

List<String> names = l.stream().map(Test::getName).
    collect(Collectors.toList());

You can't avoid at least two Stream methods, since you must first convert each Test instance to a String instance (using map() ) and then you must run some terminal operation on the Stream in order to process the Stream pipeline (in your case you chose to collect the Stream of String s into a List ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM