Java 如何使用新的 1.8 流 API 连接字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37987051/
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-11 19:53:31  来源:igfitidea点击:

How to concatenate a string with the new 1.8 stream API

javajava-8java-stream

提问by ZeDonDino

Lets say we have a simple method that should concat all names of a Person collection and return the result string.

假设我们有一个简单的方法,它应该连接 Person 集合的所有名称并返回结果字符串。

public String concantAndReturnNames(final Collection<Person> persons) {
    String result = "";
    for (Person person : persons) {
        result += person.getName();
    }
    return result;
}

Is there a way to write this code with new stream API forEach function in 1 line?

有没有办法在 1 行中使用新的流 API forEach 函数编写此代码?

采纳答案by Thomas Betous

The official documentation for what you want to do: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

你想要做什么的官方文档:https: //docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

 // Accumulate names into a List
 List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());

 // Convert elements to strings and concatenate them, separated by commas
 String joined = things.stream()
                       .map(Object::toString)
                       .collect(Collectors.joining(", "));

For your example, you would need to do this:

对于您的示例,您需要执行以下操作:

 // Convert elements to strings and concatenate them, separated by commas
 String joined = persons.stream()
                       .map(Person::getName) // This will call person.getName()
                       .collect(Collectors.joining(", "));

The argument passed to Collectors.joiningis optional.

传递给的参数Collectors.joining是可选的。