aspose file tools*
The moose likes Beginning Java and the fly likes Filtering an ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Filtering an ArrayList" Watch "Filtering an ArrayList" New topic
Author

Filtering an ArrayList

James Dudley
Greenhorn

Joined: May 20, 2011
Posts: 17
I have an Arraylist of Objects (name, value). There can the same name in the ArrayList with different values.

What I am trying to do with create a new ArrayList / HashTable that only contains 1 of each object with distinct name where the value is the most

eg arraylist could hold

Name value
A 10
B 12
A 15
B 9

New ArrayList would have
Name value
A 15
B 12


thanks
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

A Map<String,Integer> (use HashMap, not Hashtable) seems like the most obvious choice. For an object, get the current value from the map. If there is no current value or the current value is lower than the new value, overwrite the value. Otherwise do nothing.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
James Dudley
Greenhorn

Joined: May 20, 2011
Posts: 17
Thanks

Could I ask what the code would look like to do the "If there is no current value or the current value is lower than the new value, overwrite the value. Otherwise do nothing."

Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3825

Iterate the Map instance with the values in the ArrayList then you can check your condition to add them to the map. A sample code you may use:



SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
James Dudley
Greenhorn

Joined: May 20, 2011
Posts: 17
Thanks

was keeping it simple for question but what if the Integer is an Object with one of the values within the object is the value
I can pull the name and value but having problem with getting the oldvalue
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3825

Assuming you create a map like Map<String, YourClass>. The only difference is you retrieve the entire object then compare against a property of that object... Is this what you are talking about?
James Dudley
Greenhorn

Joined: May 20, 2011
Posts: 17
yes

I worked out how to get the oldvalue out but I never used a ternary operator and it is confusing me (I will ask a java dev on monday at work about them)

how would the if-else statement look like using objects

Thanks
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3825

how would the if-else statement look like using objects

Just think of the expression before the "?" mark as what you put inside the "if" statement and the colon (:) act as a the "else" keyword in that notation.
James Dudley
Greenhorn

Joined: May 20, 2011
Posts: 17
Thanks very much,
Have been able to figure it out
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Filtering an ArrayList