[英]java stream map object data member to int list
I need put the Aa and Ab to a int list in sequence: 我需要将Aa和Ab依次放入一个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));
How to do this by stream? 如何按流执行此操作? And how to do this in reverse? 以及如何反向执行此操作?
The "in reverse" I mean is create List<A>
according to List<Integer>
, because the example code is create List<Integer>
according to List<A>
. 我的意思是“反向”是根据List<Integer>
创建List<A>
,因为示例代码是根据List<A>
创建List<Integer>
。 Sorry for the brief. 对不起,简短。
Just create a Stream
of the integers of A
and flatMap
this Stream
so the integers of A anA
become part of the outer Stream
. 只要创建一个Stream
的整数A
和flatMap
这个Stream
做的整数A anA
成为外部的部分Stream
。
List<Integer> intList = list.stream()
.flatMap(anA -> Stream.of(anA.a, anA.b))
.collect(Collectors.toList());
EDIT 编辑
You asked also for the other way round: 你问也为其他方式轮:
IntStream.range(0, intList.size() / 2)
.mapToObj(i -> new A(intList.get(2*i), intList.get(2*i+1)))
.collect(Collectors.toList());
This implies a constructor in class A
: 这意味着在类A
有一个构造函数:
A(int a, int b) {
this.a = a;
this.b = b;
}
A quick test: 快速测试:
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);
}
The output is: 输出为:
[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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.