简体   繁体   中英

java stream map object data member to int list

I need put the Aa and Ab to a int list in sequence:

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> . 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 .

  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(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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM