How to match more than 1-1 entries in java thread?

I have a class MyModel and 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 create, with MyModel will be displayed with 1 or 2 Integer value (left, right or both)

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

This is how I am doing it now:

 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()); 
+5
source share
2 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()); 
+7
source

You can use the 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); 
+3
source

Source: https://habr.com/ru/post/1245128/


All Articles