Reputation: 571
I am using the following code to keep list of objects in a MAP,
Map<String, List<Rows>> map = new HashMap<String, List<Rows>>()
while( rs.next() ) {
Rows row = new Rows();
/*
* code to initialize the values of row from the record
*/
String category = rs.getString("Cat");
if(!map.containsKey(category)){
map.put(category, new ArrayList<Rows>());
}
map.get(category).add(row);
}
is it possible to sort the values for each category? how to remove an item in a specific category?
Upvotes: 0
Views: 1077
Reputation: 8465
use list to store items in ur categories. thers an API function to sort list. and use (map.remove(category) ).get(0) to get first item in ur category list
Upvotes: 0
Reputation: 115398
To remove item use remove()
method of map:
map.remove(category)
As far as I understand items of each category are stored in list, so sorting is simple:
Collections.sort(map.get(category))
You can customize your sorting using your custom Comparator
.
EDIT:
If however you wish to sort keys into your map you have to use SortedMap
, e.g. TreeMap
and probably provide your comparator that knows to compare your categories. Otherwise keys will be sorted alphabetically.
Upvotes: 1
Reputation: 18689
Is it possible to sort values in the category: Use PriorityQueue instead of list to keep values sorted as they are added.
To remove you can use map.get(category).remove(row); Or create a new class that inherits from map and overrides remove(..). You can put code here to remove from the list attached to a specific key rather than the map itself.
Upvotes: 0
Reputation: 8156
@Eme If you want a map that is sorted by its key, it is called SortedMap.
Besides if you want to remove one of the item from the List for a particular category, you can do the following:
List<Row> list = map.get(category);
list.remove(index of element you want to remove);
map.put(category, list);
Upvotes: 1