Alex Rivera | Logout

How to find elements in a collection by property?

Asked 2012-06-11T12:54:49.190
12

I have a list of items, and I want to find a list of items that have the boolean property (field variable) x=true.

I know that this can be accomplished by iteration, but I was looking for a common method to do that in commons library like Apache Commons.

Edit
Report

1 Answer

11

The problem is that iteration in Java is often much simpler and cleaner. Perhaps Java 8's Closures will fix this. ;)

Compare with @Spaeth's solution.

List<String> mixedup = Arrays.asList("A", "0", "B", "C", "1", "D", "F", "3");
List<String> numbersOnlyList = new ArrayList<>();
for (String s : mixedup) {
    try {
        // here you could evaluate you property or field
        Integer.valueOf(s);
        numbersOnlyList.add(s);
    } catch (NumberFormatException ignored) {
    }
}
System.out.println("Results of the iterated List: " + numbersOnlyList);

As you can see it much shorter and more concise.

answered 2012-06-11T13:10:22.017

Your Answer