访问地图中的最后一个条目

Gna*_*air 52 java maps hashmap

如何将特定的HashMap条目移动到Last位置?

例如,我有像这样的HashMap值:

HashMap<String,Integer> map = new HashMap<String,Integer>();

map= {Not-Specified 1, test 2, testtest 3};
Run Code Online (Sandbox Code Playgroud)

"未指定"可能处于任何位置.它可能首先出现在地图的中间.但我想把"未指定"移到最后一个位置.

我怎样才能做到这一点?提前致谢.

Sea*_*oyd 148

用一句话回答你的问题:

默认情况下,地图没有最后一个条目,它不是合同的一部分.


还有一个注意事项:对接口进行编码是很好的做法,而不是实现类(参见Joshua Bloch的Effective Java,第8章,第52项:通过接口引用对象).

所以你的声明应该是:

Map<String,Integer> map = new HashMap<String,Integer>();
Run Code Online (Sandbox Code Playgroud)

(所有地图共享一个共同的合同,因此客户不需要知道它是什么类型的地图,除非他指定一个具有扩展合同的子接口).


可能的解决方案

排序地图:

有一个子接口SortedMap,它使用基于顺序的查找方法扩展了地图界面,它有一个子接口NavigableMap,甚至可以进一步扩展它.此接口的标准实现TreeMap允许您通过自然排序(如果它们实现Comparable接口)或由提供的Comparator对条目进行排序.

您可以通过lastEntry方法访问最后一个条目:

NavigableMap<String,Integer> map = new TreeMap<String, Integer>();
// add some entries
Entry<String, Integer> lastEntry = map.lastEntry();
Run Code Online (Sandbox Code Playgroud)

链接地图:

还有LinkedHashMap的特例,HashMap实现存储了键的插入顺序.但是,没有用于备份此功能的接口,也没有直接访问最后一个密钥的方法.你只能通过在中间使用List这样的技巧来实现:

Map<String,String> map = new LinkedHashMap<String, Integer>();
// add some entries
List<Entry<String,Integer>> entryList =
    new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Entry<String, Integer> lastEntry =
    entryList.get(entryList.size()-1);
Run Code Online (Sandbox Code Playgroud)

适当的解决方案:

由于您不控制插入顺序,因此您应该使用NavigableMap接口,即您将编写一个Not-Specified最后定位条目的比较器.

这是一个例子:

final NavigableMap<String,Integer> map = 
        new TreeMap<String, Integer>(new Comparator<String>() {
    public int compare(final String o1, final String o2) {
        int result;
        if("Not-Specified".equals(o1)) {
            result=1;
        } else if("Not-Specified".equals(o2)) {
            result=-1;
        } else {
            result =o1.compareTo(o2);
        }
        return result;
    }

});
map.put("test", Integer.valueOf(2));
map.put("Not-Specified", Integer.valueOf(1));
map.put("testtest", Integer.valueOf(3));
final Entry<String, Integer> lastEntry = map.lastEntry();
System.out.println("Last key: "+lastEntry.getKey()
         + ", last value: "+lastEntry.getValue());
Run Code Online (Sandbox Code Playgroud)

输出:

最后一个键:未指定,最后一个值:1

使用HashMap的解决方案:

如果你必须依赖HashMaps,仍然有一个解决方案,使用a)上述比较器的修改版本,b)使用Map的entrySet初始化的List和c)Collections.sort()帮助器方法:

    final Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("test", Integer.valueOf(2));
    map.put("Not-Specified", Integer.valueOf(1));
    map.put("testtest", Integer.valueOf(3));

    final List<Entry<String, Integer>> entries =
        new ArrayList<Entry<String, Integer>>(map.entrySet());
    Collections.sort(entries, new Comparator<Entry<String, Integer>>(){

        public int compareKeys(final String o1, final String o2){
            int result;
            if("Not-Specified".equals(o1)){
                result = 1;
            } else if("Not-Specified".equals(o2)){
                result = -1;
            } else{
                result = o1.compareTo(o2);
            }
            return result;
        }

        @Override
        public int compare(final Entry<String, Integer> o1,
            final Entry<String, Integer> o2){
            return this.compareKeys(o1.getKey(), o2.getKey());
        }

    });

    final Entry<String, Integer> lastEntry =
        entries.get(entries.size() - 1);
    System.out.println("Last key: " + lastEntry.getKey() + ", last value: "
        + lastEntry.getValue());

}
Run Code Online (Sandbox Code Playgroud)

输出:

最后一个键:未指定,最后一个值:1


卢声远*_* Lu 17

HashMap没有"最后位置",因为它没有排序.

你可以使用其他的Map工具java.util.SortedMap,最受欢迎的是TreeMap.


Pet*_*rey 5

A SortedMap是逻辑/最佳选择,但另一种选择是使用LinkedHashMap维护两种顺序模式的a,最近添加的最后一种,最近访问的最后一种.有关更多详细信息,请参阅Javadocs.