Java 8 create map a list of a complex type to list of one of its fields -
i have list complex type , want figure neat way construct list 1 of fields using java 8's streams. let's take example:
public static class test { public test(string name) { this.name = name; } public string getname() { return name; } private string name; // other fields } and imagine have list<test> l;. want create new list contains values of name of elements in l. 1 possible solution found following:
list<string> names = l.stream().map(u ->u.getname()). collect(collectors.<string> tolist()); but wondering if there better way - map list of given type list of different type.
using method references shorter :
list<string> names = l.stream().map(test::getname). collect(collectors.tolist()); you can't avoid @ least 2 stream methods, since must first convert each test instance string instance (using map()) , must run terminal operation on stream in order process stream pipeline (in case chose collect stream of strings list).
Comments
Post a Comment