4

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);
lbalazscs
  • 17,474
  • 7
  • 42
  • 50
Adam_G
  • 7,337
  • 20
  • 86
  • 148
  • Possible duplicate of http://stackoverflow.com/questions/7679819/how-to-add-element-at-specific-index-position-in-linkedhashmap – wassgren Dec 30 '14 at 20:38
  • 1
    No. Even though `LinkedHahsMap` respects insertion order on iteration, it still implements `Map` for which there is no such method as "put an item in first position". Among collections, only a `List` can do that reliably. – fge Dec 30 '14 at 20:40

3 Answers3

4

For the case of moving items to the front, you could create a new LinkedHashMap with your preferred order. e.g.

LinkedHashMap<K,V>  newMap = new LinkedHashMap<K,V>(oldMap.size());
V valueIWantToBeFirst= oldMap.remove(keyIWantToBeFirst);
newMap.put(keyIWantToBeFirst, valueIWantToBeFirst);
newMap.putAll(oldMap);  // keeps previous order for all remaining entries
user949300
  • 15,364
  • 7
  • 35
  • 66
1

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);
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
0

public void sortList() {

    ArrayList<String> objectsToOrder=new ArrayList<>(object.keySet());

    ArrayList<String> orderedObjects=new ArrayList<>();
    orderedObjects.add("A");
    orderedObjects.add("B");
    orderedObjects.add("C");
    orderedObjects.add("D");
    orderedObjects.add("E");

    LinkedHashMap<String,ArrayList<QueryRow>>  orderedlist = new LinkedHashMap<String,ArrayList<QueryRow>>(object.size());

  for(int i=0;i<orderedObjects.size();i++){
      if(objectsToOrder.contains(orderedObjects.get(i))){
          ArrayList<QueryRow> valueIWantToBeFirst= object.remove(orderedObjects.get(i));
          orderedlist.put(orderedObjects.get(i),valueIWantToBeFirst);
      }
  }

    orderedlist.putAll(new LinkedHashMap<String, ArrayList<QueryRow>>(object));

    object.clear();

    object.putAll(new LinkedHashMap<String, ArrayList<QueryRow>>(orderedlist));

}