如何提取列表中特定属性的所有元素? [英] How to extract all elements of a specific property in a list?
本文介绍了如何提取列表中特定属性的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能最好地获得以下结构的所有name字符串元素:
how can I best get all "name" string elements of the following structure:
class Foo {
List<Bar> bars;
}
class Bar {
private String name;
private int age;
}
我的方法是:
List<String> names = new ArrayList<String>();
for (Bar bar : foo.getBars()) {
names.add(bar.getName());
}
这可能有效,但在java中没有。集合
我可以这样写:
Collections.getAll(foo.getBars(),name);
?
This might work, but isn't there something in java.Collections
where I just can write like this:
Collections.getAll(foo.getBars(), "name");
?
推荐答案
使用Java 8:
List<String> names =
foo.getBars().stream().map(Bar::getName).collect(Collectors.toList());
这篇关于如何提取列表中特定属性的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文