我有一个对象列表,让我们说List<Example>
,类示例有一个成员a是一个字符串:
class Example {
String a;
String b;
}
现在,我希望仅使用列表中每个成员的 a 元素,从List<Example>
转到List<String>
。
当然这对于循环来说很容易,但我试图找到类似于C ++中的算法的东西,它可以直接执行此操作。
问题:从列表投放到列表的最简单方法是什么,其中值是a
的字段Example
?
编辑:这就是我对for循环的意思:
List<String> result = new ArrayList<String>();
for(Example e : myList)
result.add(e.a);
return result;
答案 0 :(得分:3)
这是使用Java 8的声明性流映射的简单解决方案:
class Example {
String a;
String b;
// methods below for testing
public Example(String a) {
this.a = a;
}
public String getA() {
return a;
}
@Override
public String toString() {
return String.format("Example with a = %s", a);
}
}
// initializing test list of Examples
List<Example> list = Arrays.asList(new Example("a"), new Example("b"));
// printing original list
System.out.println(list);
// initializing projected list by mapping
// this is where the real work is
List<String> newList = list
// streaming list
.stream()
// mapping to String through method reference
.map(Example::getA)
// collecting to list
.collect(Collectors.toList());
// printing projected list
System.out.println(newList);
<强>输出强>
[Example with a = a, Example with a = b]
[a, b]
<强>文档强>
答案 1 :(得分:1)
您可以在java8中使用流
List<Example> l = Arrays.asList(new Example("a", "a"), new Example("b", "b"), new Example("c", "c"),
new Example("d", "d"));
List<String> names = l.stream().map(Example::getA).collect(Collectors.toList());
System.out.println(names);