在 Java 中这个 for 循环的等效 lambda 表达式是什么?
我只想在一行中打印列表对象的名称。
for(Attribute attr : dataSet.getAttributeList()){
System.out.print(attr.getName() + " ");
}
我尝试了以下但没有任何运气,我只得到了流的身份哈希码。
Arrays.asList(dataSet.getAttributeList().stream().map(p -> p.getName()));
最佳答案
假设您的名称属性是一个 String
,继续使用您的 Stream
管道。使用内置的 Collector
收集名称,它将值与每个元素之间的分隔符连接起来:Collectors.joining
:
Returns a
Collector
that concatenates the input elements, separated by the specified delimiter, in encounter order.
你可以删除不必要的Arrays.asList
,反正这是不正确的;它采用数组而不是流或字符串作为参数。
System.out.println(
dataSet.getAttributeList().stream()
.map(p -> p.getName())
.collect(Collectors.joining(" "))
);
您也可以选择使用方法引用而不是 lambda 表达式:
.map(Attribute::getName)
关于java - 等效的 lambda 表达式,获取列表中每个对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52975499/