Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - remove last known item from HASHMAP on MAP!s

Tags:

java

arraylist

OK so this is a BIT different. I have a new HashMap

private Map<String, Player> players = new HashMap<String, Player>();

How do I remove last known item from that? Maybe somethign like this?

hey = Player.get(players.size() - 1);
Player.remove(hey);
like image 952
test Avatar asked Dec 12 '22 20:12

test


2 Answers

The problem is, a HashMap is not sorted like a list. The internal order depends on the hashCode() value of the key (e.g. String). You can use a LinkedHashMap which preserves the insert order. To remove the last entry on this you can use an iterator in combination with a counter which compares to the size and remove the last entry.

It's so easy. Try this:

Map<String, Player> players = new LinkedHashMap<String, Players>();
List<String> list = new ArrayList<String>(players.keySet());
map.remove(list.get(list.size()-1));
like image 168
fprobst Avatar answered Dec 25 '22 19:12

fprobst


I'm a little bit confused. First of all, you're saying that you've got a new ArrayList and you're illustrating this with a line that creates a new HashMap. Secondly, does the Player class really have static methods like get(int) and remove(Object)?

HashMap doesn't have a particular order, ArrayList (as any other List) does.

Removing from an ArrayList

If you've got a list of players, then you can do the following:

private List<Player> players = new ArrayList<Player>();
// Populate the list of players
players.remove(players.size() - 1);

Here, I've used the remove(int) method of List, which allows to remove an item at an arbitrary index.

Removing from a HashMap

If you've got a map of players, there's no such thing as "the last item". Sure, you can iterate over the map and one of the items will pop out last, but that doesn't mean anything. Therefore, first you have to find out what you want to remove. Then you can do the following:

private Map<String, Player> players = new HashMap<String, Player>();
// Populate the map of players
// Find the key of the player to remove
players.remove(toRemove);

Here, I've used the remove(Object) method of Map. Note that in order to remove some key-value pair, you have to show the key, not the value.

like image 22
Bolo Avatar answered Dec 25 '22 20:12

Bolo