javacollectionshashmaplinkedhashmap

Move Item in LinkedHashMap


Is there a way to move an item within a LinkedHashMap? Specifically, I'd like to move an item to the first position. I know that if I wanted to add an item to the end, I could just do:

LinkedHashMap<String,Integer> items = new LinkedHashMap<String,Integer>();
//...add some items
int i = items.get("removedItem");
items.remove("removedItem");
items.put("removedItem",i);

Solution

  • It you want to keep the same Map instance, you can do it in 3 lines like this.

    Map<Integer, String> map = new LinkedHashMap<>();
    map.put(1, "One");
    map.put(2, "Two");
    map.put(3, "Three");
    map.put(4, "Four");
    
    Map<Integer, String> copy = new LinkedHashMap<>(map);
    map.keySet().retainAll(Collections.singleton(3));
    map.putAll(copy);
    
    System.out.println(map);