我的目标:获取LinkedList
个User
并以优雅的Java-8方式提取LinkedList
个用户名。
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;
}
}
我很难尝试将Stream
对象转换为LinkedList
。我可以将它变成一个数组(Stream::toArray()
)并将其转换为List
(Arrays.asList(Stream::toArray())
),但这似乎是......不,谢谢。
我错过了什么吗?
答案 0 :(得分:73)
您可以使用Collector
这样的结果将结果放入LinkedList
:
LinkedList<String> usernames2 = users.stream()
.map(User::getUsername)
.collect(Collectors.toCollection(LinkedList::new));