容器的投影,即将 List<Object> 转换为 List<Object.Member> 的方法

Beg*_*ner 5 java list java-stream collectors

我有一个对象列表,可以说List<Example>,示例类有一个成员 a,它是一个字符串:

class Example {
    String a;
    String b;
}
Run Code Online (Sandbox Code Playgroud)

现在我想通过仅使用列表中每个成员的aList<Example>元素来获取to 。List<String>

当然,使用循环很容易做到这一点,但我试图找到类似于 C++ 中的算法的东西,可以直接做到这一点。

问题:从列表投影到列表的最简单方法是什么,其中值是a的字段Example


编辑:这就是我所说的 for 循环的意思:

List<String> result = new ArrayList<String>();
for(Example e : myList)
    result.add(e.a);
return result;
Run Code Online (Sandbox Code Playgroud)

Men*_*ena 4

这是使用 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);
Run Code Online (Sandbox Code Playgroud)

输出

[Example with a = a, Example with a = b]
[a, b]
Run Code Online (Sandbox Code Playgroud)

文档

  • Java 8 流上的通用包 API在这里
  • 具体APIStream#map方法见这里

  • 有趣的是,您可以使用与该解决方案相同的技术来构建测试数据: `List&lt;Example&gt; list=Stream.of("a","b").map(Example::new).collect( Collectors.toList());` (2认同)