Java 将对象流转换为属性链表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22647486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:04:41  来源:igfitidea点击:

Turn a stream of objects into a linked list of attributes

javalambdajava-8java-stream

提问by ryvantage

My goal: Take a LinkedListof Users and extract a LinkedListof their usernames in an elegant, Java-8 way.

我的目标:采取LinkedListUserS和提取LinkedList在一个优雅的,Java的8路的用户名。

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 Streamobject 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.

我在尝试将Stream对象转换为LinkedList. 我可以把它变成一个数组 ( Stream::toArray()) 然后把它变成一个List( Arrays.asList(Stream::toArray())) 但这似乎是......不,谢谢。

Am I missing something?

我错过了什么吗?

采纳答案by Keppil

You can use a Collectorlike this to put the result into a LinkedList:

您可以使用这样的 aCollector将结果放入 a 中LinkedList

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