MahmoudS MahmoudS - 5 months ago 48
Java Question

How to find elements in a collection by property?

I have a list of items, and I want to find a list of items that have the boolean property


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.


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
    } catch (NumberFormatException ignored) {
System.out.println("Results of the iterated List: " + numbersOnlyList);

As you can see it much shorter and more concise.