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

Turn a stream of objects into a linked list of attributes

提问人:ryvantage 提问时间:3/26/2014 最后编辑:Pshemoryvantage 更新时间:11/3/2015 访问量:39271

问:

我的目标是:以一种优雅的 Java-8 方式提取他们的用户名。LinkedListUserLinkedList

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;
    }
}

我被困在试图将对象转换为.我可以把它变成一个数组()并将其变成一个(),但看起来就是这样......不,谢谢。StreamLinkedListStream::toArray()ListArrays.asList(Stream::toArray())

我错过了什么吗?

Lambda Java-8 Java

评论


答:

128赞 Keppil 3/26/2014 #1

你可以用这样的方法把结果放到一个 :CollectorLinkedList

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