如何将字符串与新的1.8流API连接起来

ZeD*_*ino 35 java java-8 java-stream

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

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

有没有办法用1行的新流API forEach函数编写这段代码?

Tho*_*ous 47

您要执行的操作的官方文档: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(", "));
Run Code Online (Sandbox Code Playgroud)

对于您的示例,您需要这样做:

 // 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(", "));
Run Code Online (Sandbox Code Playgroud)

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

  • 您可能希望使用 String::valueOf 而不是 Object::toString 来保证空值安全。 (5认同)
  • 底部的代码块是完美的,我需要的一切:)谢谢! (2认同)