在LinkedHashMap中移动项目 [英] Move Item in LinkedHashMap

查看:139
本文介绍了在LinkedHashMap中移动项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 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);


推荐答案

要保持相同的 Map 实例,您可以在3行中完成此操作。

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

这篇关于在LinkedHashMap中移动项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆