My goal: Take a LinkedList
of User
s and extract a LinkedList
of their usernames in an elegant, Java-8 way.
public static void main(String[] args) {
LinkedList<User> users = new LinkedList<>();
users.add(new User(1, "User1"));
users.add(new User(2, "User2"));
users.add(new User(3, "User3"));
// Vanilla Java approach
LinkedList<String> usernames = new LinkedList<>();
for(User user : users) {
System.out.println(user.getUsername());
usernames.add(user.getUsername());
}
System.out.println("Usernames = " + usernames.toString());
// Java 8 approach
users.forEach((user) -> System.out.println(user.getUsername()));
LinkedList<String> usernames2 = users.stream().map(User::getUsername). // Is there a way to turn this map into a LinkedList?
System.out.println("Usernames = " + usernames2.toString());
}
static class User {
int id;
String username;
public User() {
}
public User(int id, String username) {
this.id = id;
this.username = username;
}
public void setUsername(String username) {
this.username = username;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public int getId() {
return id;
}
}
I am stuck trying to convert the Stream
object into a LinkedList
. I could turn it into an array (Stream::toArray()
) and turn that into a List
(Arrays.asList(Stream::toArray())
) but that just seems so... no thank you.
Am I missing something?
You can use a Collector
like this to put the result into a LinkedList
:
LinkedList<String> usernames2 =
users.stream()
.map(User::getUsername)
.collect(Collectors.toCollection(LinkedList::new));