1

I would like to get subsets of elements of a Java List by specifying some of their parameters. Each element has different characteristics, e.g. x-position, y-position, width, height and type. Now I want to get all elements, which position is in a specific interval, or which width or height is not greater than a given value, or which type equals some String.

My actual solution is, that I wrote a bunch of subset()-functions to apply in each different case.

public List<Element> subsetByPositionX(
    List<Element> elements, int minX, int maxX) { /*...*/ }

public List<Element> subsetByPositionY(
    List<Element> elements, int minY, int maxY) { /*...*/ }

public List<Element> subsetByMaxWidth(
    List<Element> elements, int maxWidth) { /*...*/ }

// some more subset methods for height and width

public List<Element> subsetByType(
    List<Element> elements, String... types) { /*...*/ }

I'm a bit unlucky about this, because it is not very generic. Is there a more elegant way to subset elements by different kinds of characteristics?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
lupi5
  • 91
  • 1
  • 6
  • 1
    So does each of these methods just [filter the list by some predicate](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#filter-java.util.function.Predicate-)? – Chris Martin Aug 09 '15 at 09:41
  • Yes, each method returns a list of elements which matches the specified parameters by some rules (e.g. event.x > minX, element.width < maxWidth, types.contains(element.type), etc.). According to your comment, I read something about Streams and their filter()-function. I think that this can be a good solution. – lupi5 Aug 09 '15 at 09:54

0 Answers0