-1

I have a arraylist of objects Box and i need to find all id of Boxes with more than one specific style. Example:

ArrayList<Box> boxes = new ArrayList<>();
Style s1 = new Style("black",160);
Style s2 = new Style("yellow", 150);
Style s3 = new Style("green", 150);
boxes.add(new Box(s1));//id 0
boxes.add(new Box(s2));
boxes.add(new Box(s2));
boxes.add(new Box(s3));//id 3

and need to find all boxes with style s2 and s3 for example (This styles can be n and they will be store in array). Result will be {1,2,3}. Is there a effective way to do that?

class Box{

  private int id;
  private Style style;

  public Box(){}
  //GETTERS AND SETTERS
}

class Style{
  private String background;
  private int width;

  public Style(){}

  //GETTERS AND SETTERS
}
lmana
  • 1
  • 1
    Does this answer your question? [What is the best way to filter a Java Collection?](https://stackoverflow.com/questions/122105/what-is-the-best-way-to-filter-a-java-collection) – OH GOD SPIDERS Apr 01 '20 at 13:26
  • 1
    `boxes.stream().filter(e->Arrays.asList(s2, s3).contains(e)).collect(Collectors.toList());` – robothy Apr 01 '20 at 13:29
  • @robothy Why would a stream of `Box` objects contain a `Style`? (This is why you should use a more meaningful variable name than `e`. Like `b` or `box`.) – VGR Apr 01 '20 at 13:35
  • It should be: `boxes.stream().filter(box->Arrays.asList(s2, s3).contains(box.getStyle())).collect(Collectors.toList());` Thanks for your correction.@VGR – robothy Apr 01 '20 at 13:41

2 Answers2

0

Use Java streams. Assuming your style class has an equals() methods defined,

boxes.stream().filter(box -> box.getStyle().equals(s1) || box.getStyle().equals(s2)).collect(Collections.toSet())
Satyan Raina
  • 990
  • 5
  • 15
0

You could have Style be an Enumeration since it's probably going to be fairly finite. You can also make use of the Enums implementation of equals because of this and keep it simple. Every Box can still be comprised of a Style reference.

You could then create a method that checks if a List of Boxes contains any of the Style references from a Set of them.

    enum Style {
        BLACK(160),
        YELLOW(150),
        GREEN(150);

        private final int width;

        Style(int width) {
            this.width = width;
        }
    }
    static List<Box> forStyle(Set<Style> styles, List<Box> boxes) {
        return boxes.stream()
                .filter(box -> styles.contains(box.style))
                .collect(Collectors.toList());
    }
        ArrayList<Box> boxes = new ArrayList<>();

        boxes.add(new Box(0, Style.BLACK));
        boxes.add(new Box(1, Style.YELLOW));
        boxes.add(new Box(2, Style.YELLOW));
        boxes.add(new Box(3, Style.GREEN));

        List<Box> greenAndYellow = forStyle(Arrays.asList(Style.BLACK, Style.YELLOW), boxes);
Jason
  • 5,154
  • 2
  • 12
  • 22