我想在ArrayList有一个对象的某个属性的值列表。 假设我有这样一个类:
public class Foo { private String b, a, r; //Constructor... //Getters... }然后我创建一个ArrayList<Foo> :
ArrayList<Foo> fooList = new ArrayList<>(); fooList.add(new Foo("How", "Hey", "Hey")); fooList.add(new Foo("Can", "Hey", "Hey")); fooList.add(new Foo("I", "Hey", "Hey")); fooList.add(new Foo("Get", "Hey", "Hey")); fooList.add(new Foo("Those?", "Hey", "Hey"));在ArrayList<Foo> ,是否可以获取Foo的某个属性的List而不必使用for循环迭代我的ArrayList ? 在Objective-c中,也许某些东西与valueforkey相似 。 如果我有一个包含How , Can , I , Get和Those的ArrayList<String> ,这将使用TextUtils.join()更容易打印值。
I'd like to have a list of values for a certain property of an object inside an ArrayList. Supposing I have a class like this:
public class Foo { private String b, a, r; //Constructor... //Getters... }Then I create an ArrayList<Foo>:
ArrayList<Foo> fooList = new ArrayList<>(); fooList.add(new Foo("How", "Hey", "Hey")); fooList.add(new Foo("Can", "Hey", "Hey")); fooList.add(new Foo("I", "Hey", "Hey")); fooList.add(new Foo("Get", "Hey", "Hey")); fooList.add(new Foo("Those?", "Hey", "Hey"));In an ArrayList<Foo>, is it possible to get a List of a certain property of Foo without having to iterate over my ArrayList using a for loop? Maybe something simillar to valueforkey in Objective-c. This would make easier to print values using TextUtils.join() if I had an ArrayList<String> containing How, Can, I, Get, and Those.
最满意答案
使用Java 8,您可以流式传输,映射和收集:
List<String> list = fooList.stream() .map(Foo::getProp) .collect(Collectors.toList());如果您有Guava,您可以像这样获得列表的转换视图:
List<String> list = Lists.transform(fooList, Foo::getProp);Java 7版本:
List<String> list = Lists.transform(fooList, new Function<Foo, String>() { @Override public String apply(Foo foo) { return foo.getProp(); } });Using Java 8, you can stream, map and collect:
List<String> list = fooList.stream() .map(Foo::getProp) .collect(Collectors.toList());If you have Guava, you can get a transformed view of your list like this:
List<String> list = Lists.transform(fooList, Foo::getProp);The Java 7 version:
List<String> list = Lists.transform(fooList, new Function<Foo, String>() { @Override public String apply(Foo foo) { return foo.getProp(); } });更多推荐
发布评论