I am having a java ArrayList of integer
ArrayList <Integer> ageList = new ArrayList <Integer>();
I am having some integer values in this arrayList. I want to create a new ArrayList which has all elements in the above arrayList which passes a condition, like value between 25 and 35. ie if my ageList contains values
{12,234,45,33,28,56,27}
my newList should contain
{33,28,27}
How can I achieve this?
Note: I came to java from objective C background, where I used NSPredicate to easly do such kind of things..Any similiar methods in java?
There is no “filter” facility in the standard API. (There is in Guava and Apache Commons however.) You’ll have to create a new list, loop through the original list and manually add the elements in range 25-35 to the new list.
If you have no intention to keep the original list, you could remove the elements out of range using an
Iteratorand theIterator.removemethod.If you have no duplicates in your list, you could use a
TreeSetin which case you could get all elements in a specific range usingheadSet/tailSet.Related question: (possibly even a duplicate actually)