[英]java stream map object data member to int list
我需要將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));
如何按流執行此操作? 以及如何反向執行此操作?
我的意思是“反向”是根據List<Integer>
創建List<A>
,因為示例代碼是根據List<A>
創建List<Integer>
。 對不起,簡短。
只要創建一個Stream
的整數A
和flatMap
這個Stream
做的整數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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.