开发者

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.


  1. Create a Hashtable to keep track of the current greatest-aged Foo that you've come across.
  2. Loop over your ArrayList. For each Foo:
    1. if the Hashtable doesn't contain an item with the given name, add the item with its name as the key.
    2. if the Hashtable contains a Foo with the given name, check its age.
      1. 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 ) );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜