将对象流转换为链接的属性列表

时间:2014-03-25 22:17:49

标签: java lambda java-8 java-stream

我的目标:获取LinkedListUser并以优雅的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())并将其转换为ListArrays.asList(Stream::toArray())),但这似乎是......不,谢谢。

我错过了什么吗?

1 个答案:

答案 0 :(得分:73)

您可以使用Collector这样的结果将结果放入LinkedList

LinkedList<String> usernames2 = users.stream()
                                .map(User::getUsername)
                                .collect(Collectors.toCollection(LinkedList::new));