Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 812
Viet Avatar asked Mar 16 '16 04:03

Viet


1 Answers

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());
like image 130
Tagir Valeev Avatar answered Sep 26 '22 02:09

Tagir Valeev