Java integer ArrayList return elements within a specific range
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 conta开发者_运维技巧in
{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 Iterator
and the Iterator.remove
method.
If you have no duplicates in your list, you could use a TreeSet
in which case you could get all elements in a specific range using headSet
/ tailSet
.
Related question: (possibly even a duplicate actually)
- What is the best way to filter a Java Collection?
Well, with Guava you could write:
Iterable<Integer> filtered = Iterables.filter(list, new Predicate<Integer>() {
@Override public boolean apply(Integer value) {
return value >= 25 && value <= 35;
}
});
List<Integer> newList = Lists.newArrayList(filtered);
You may use foreach loop
List<Integer> newList = new ArrayList<Integer>();
for (Integer value : ageList) {
if (value >= 25 && value <= 35) {
newList.add(value);
}
}
Try this:
ArrayList<Integer> newList = new ArrayList<Integer>(ageList);
for (Iterator<Integer> it = newList.iterator(); it.hasNext();) {
int n = it.next();
if (n < 25 || n > 35)
it.remove();
}
No there is no built in functionality in java [AFAIK].
The steps can be:
- Loop through ageList.
- Check for condition.
- If condition is success then add that element to new list or else do nothing.
Sample code:
List<Integer> ageList = new ArrayList<Integer>();
//-- add data in ageList
List<Integer> newList = new ArrayList<Integer>();
for (Integer integer : ageList) {
if(integer >= 25 && integer <= 35)
newList.add(integer);
}
Not possible with the standard JCF. You'll have to iterate.
Consider using Guava. It has such kind of utilities.
http://code.google.com/p/guava-libraries/
Iterate over it and just add the ones that match? It's 3 lines of code... 4 including the new ArrayList declration.
精彩评论