Java 流:将对象数据成员映射到 int 列表



我需要按顺序将A.aA.b放到int列表中:

class A {
int a;
int b;
}
A a = new A();
a.a = 1;
a.b = 2;
List<A> list = Arrays.asList(a);
List<Integer> intList = list.stream().map(?).collect(Collectors.toList());
assert intList.equals(Arrays.asList(1,2));

如何使用 Java 流执行此操作?
以及如何反向执行此操作?

注意

通过">反向",我的意思是根据List<Integer>创建一个List<A>,因为示例代码是根据List<A>创建List<Integer>的。

只需创建A整数的StreamflatMapStream,以便A anA的整数成为外部Stream的一部分。

List<Integer> intList = list.stream()
.flatMap(anA -> Stream.of(anA.a, anA.b))
.collect(Collectors.toList());

编辑
你也要求相反的方式:

IntStream.range(0, intList.size() / 2)
.mapToObj(i -> new A(intList.get(2*i), intList.get(2*i+1)))
.collect(Collectors.toList());

这意味着类A中的构造函数:

A(int a, int b) {
this.a = a;
this.b = b;
}

快速测试:

public static void main(String[] args) throws Exception {
List<A> list = Arrays.asList(new A(1, 2), new A(3, 4), new A(11, 22));
List<Integer> intList = list.stream().flatMap(anA -> Stream.of(anA.a, anA.b)).collect(Collectors.toList());
System.out.println(intList);
List<A> aList = IntStream.range(0, intList.size() / 2).mapToObj(i -> new A(intList.get(2 * i), intList.get(2 * i + 1))).collect(Collectors.toList());
System.out.println(aList);
}

输出为:

[1, 2, 3, 4, 11, 22]
[[1|2], [3|4], [11|22]]
List<Integer> intList = Arrays.asList(A).stream()
.flatMap(A -> Stream.of(A.a, A.b))
.collect(Collectors.toList());
List<Integer> reverseIntList = Arrays.asList(A).stream()
.flatMap(A -> Stream.of(A.a, A.b))
.collect(LinkedList::new, LinkedList::addFirst, (res, tmp) -> tmp.forEach(res::addFirst));

最新更新