Viet
Viet

Reputation: 3409

How to map more than 1-1 record in java stream?

I have a MyModel class and a List<MyModel>

public static class MyModel{
    private int left;
    private int right;
    private int state = 0;
    public MyModel(int left, int right, int state){
        this.left = left;
        this.right = right;
        this.state = state;
    }
    public int getLeft() {
        return left;
    }
    public void setLeft(int left) {
        this.left = left;
    }
    public int getRight() {
        return right;
    }
    public void setRight(int right) {
        this.right = right;
    }
    public int getState() {
        return state;
    }
    public void setState(int state) {
        this.state = state;
    }
}

and i want to produce, with a MyModel will map with 1 or 2 Integer value (left,right or both)

I can do with 1 but don't know how to do with 2

This is how I am currently doing :

List<MyModel> models = new ArrayList<MyModel>();
models.add(new MyModel(1, 2, 1));
models.add(new MyModel(3, 4, 2));
models.add(new MyModel(5, 6, 3));
List<Integer> result = models.stream().map(p -> {
    switch (p.getState()) {
    case 1:
        return p.getLeft();
    case 2:
        return p.getRight();
    case 3:
        //Problem here i need add left and right into result list 
    default:
        return p.getLeft();             
    }
}).collect(Collectors.toList());

Upvotes: 5

Views: 566

Answers (2)

babanin
babanin

Reputation: 3584

You can use Collector API:

List<Integer> result = models.stream().collect(ArrayList::new, (r, p) -> {
    switch (p.getState()) {
      case 1:
        r.add(p.getLeft());
        break;
      case 2:
        r.add(p.getRight());
        break;
      case 3:
        r.add(p.getLeft());
        r.add(p.getRight());
        break;
      default:
        r.add(p.getLeft());
        break;
    }
}, ArrayList::addAll);

Upvotes: 3

Tagir Valeev
Tagir Valeev

Reputation: 100169

Use flatMap, it does exactly what you need:

List<Integer> result = models.stream().flatMap(p -> {
    switch (p.getState()) {
    case 1:
        return Stream.of(p.getLeft());
    case 2:
        return Stream.of(p.getRight());
    case 3:
        return Stream.of(p.getLeft(), p.getRight());
    default:
        return Stream.of(p.getLeft());
        // you can also return Stream.empty() if appropriate
    }
}).collect(Collectors.toList());

Upvotes: 7

Related Questions