访问 Map 中的最后一个条目

Accessing the last entry in a Map(访问 Map 中的最后一个条目)
本文介绍了访问 Map 中的最后一个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to move a particular HashMap entry to Last position?

例如,我有这样的 HashMap 值:

For Example, I have HashMap values like this:

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

map= {Not-Specified 1, test 2, testtest 3};

未指定"可以出现在任何位置.它可能出现在地图的最前面或中间.但我想将未指定"移动到最后一个位置.

"Not-Specified" may come in any position. it may come first or in the middle of the map. But i want to move the "Not-Specified" to the last position.

我该怎么做?提前致谢.

How can I do that? thanks in advance.

推荐答案

一句话回答你的问题:

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

附带说明:最好针对接口而不是实现类进行编码(请参阅 Effective Java by Joshua Bloch,第 8 章,第 52 项:通过接口引用对象).

And a side note: it's good practice to code against interfaces, not the implementation classes (see Effective Java by Joshua Bloch, Chapter 8, Item 52: Refer to objects by their interfaces).

所以你的声明应该是:

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

(所有地图共享一个公共合约,因此客户端不需要知道它是哪种地图,除非他指定带有扩展合约的子接口).

(All maps share a common contract, so the client need not know what kind of map it is, unless he specifies a sub interface with an extended contract).

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

There is a sub interface SortedMap that extends the map interface with order-based lookup methods and it has a sub interface NavigableMap that extends it even further. The standard implementation of this interface, TreeMap, allows you to sort entries either by natural ordering (if they implement the Comparable interface) or by a supplied Comparator.

您可以通过 lastEntry 方法:

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

链接地图:

还有LinkedHashMap,一个 HashMap 实现,存储键的插入顺序.然而,没有接口来备份这个功能,也没有直接的方法来访问最后一个键.您只能通过使用 List 等技巧来做到这一点:

Linkedmaps:

There is also the special case of LinkedHashMap, a HashMap implementation that stores the order in which keys are inserted. There is however no interface to back up this functionality, nor is there a direct way to access the last key. You can only do it through tricks such as using a List in between:

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

正确的解决方案:

由于您不控制插入顺序,您应该使用 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());

输出:

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

Last key: Not-Specified, last value: 1

使用HashMap的解决方案:

如果一定要依赖HashMaps,还是有解决办法的,使用a)上述比较器的修改版,b)a List 使用地图的 entrySet 和 c) Collections.sort() 辅助方法:

SolutionusingHashMap:

If you must rely on HashMaps, there is still a solution, using a) a modified version of the above comparator, b) a List initialized with the Map's entrySet and c) the Collections.sort() helper method:

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

}

输出:

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

Last key: Not-Specified, last value: 1

这篇关于访问 Map 中的最后一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)