Filter out objects in ArrayList
I have an ArrayList of Foo objects. Foo's properties are String name and int age. I don't want more than one of the same name, so when the开发者_Go百科 same name, keep only the greatest age. I'm looking an idea to get me going in Java.
- Create a Hashtable to keep track of the current greatest-aged Foo that you've come across.
- Loop over your ArrayList. For each Foo:
- if the Hashtable doesn't contain an item with the given name, add the item with its name as the key.
- if the Hashtable contains a Foo with the given name, check its age.
- if the age of the current Foo is greater than the age of the Foo in the Hashtable, replace the Foo in the Hashtable with the one you're looking at.
Map<String , Foo> foos = new HashMap<String , Foo>();
for ( Foo foo : listFoos ) {
Foo currentFoo = foos.get(foo.getName());
if ( currentFoo == null ) {
foos.add(foo.getName(), foo);
continue;
}
if ( currentFoo.getAge() > foo.getAge() )
continue;
foos.put(foo.getName() , foo);
}
Implement equals and hashCode() on Foo to use the name property.
Place each (name,age) pair in the ArrayList<Foo>
into a HashMap<String,Foo>
. If the HashMap
already contains a key with the same name, then compare the ages and replace accordingly.
Then after you're done, replace the elements in the ArrayList
with the elements in the HashMap
.
HashMap<String,Foo> hashmap = new HashMap<String,Foo>();
for( Foo foo : arraylist ) {
if( !hashmap.contains( foo.name ) || hashmap.get( foo.name ).age < foo.age )
hashmap.put( foo.name, foo );
}
arraylist.clear();
for( String name : hashmap.keySet() ) {
arraylist.add( hashmap.get( name ) );
}
精彩评论