在LinkedHashMap中移动项目

时间:2014-12-30 20:35:50

标签: java collections hashmap linkedhashmap

有没有办法在LinkedHashMap内移动项目?具体来说,我想将项目移动到第一个位置。我知道如果我想在最后添加一个项目,我可以这样做:

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

3 个答案:

答案 0 :(得分:3)

对于将项目移到前面的情况,您可以使用首选订单创建新的LinkedHashMap。 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

答案 1 :(得分:1)

你希望保持相同的Map实例,你可以用3行这样做。

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);

答案 2 :(得分: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));

}