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

2022-09-01 10:05:01

我的目标:取一个s,并以一种优雅的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())

我错过了什么吗?


答案 1

您可以使用类似这样的方法将结果放入:CollectorLinkedList

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

答案 2

推荐