Java 访问 Map 中的最后一个条目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3527216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:33:24  来源:igfitidea点击:

Accessing the last entry in a Map

javamapshashmap

提问by Gnaniyar Zubair

How to move a particular HashMap entry to Last position?

如何将特定的 HashMap 条目移动到最后一个位置?

For Example, I have HashMap values like this:

例如,我有这样的 HashMap 值:

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.

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

采纳答案by Sean Patrick Floyd

To answer your question in one sentence:

一句话回答你的问题:

Per default, Maps don't have a last entry, it's not part of their contract.

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



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

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

So your declaration should read:

所以你的声明应该是:

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

(所有地图共享一个共同的合约,所以客户端不需要知道它是什么类型的地图,除非他指定了一个带有扩展合约的子接口)。



Possible Solutions

可能的解决方案

Sorted Maps:

排序地图:

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

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

You can access the last entry through the lastEntrymethod:

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

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

Linked maps:

关联地图:

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:

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

Proper Solution:

正确的解决方案:

Since you don't control the insertion order, you should go with the NavigableMap interface, i.e. you would write a comparator that positions the Not-Specifiedentry last.

由于您不控制插入顺序,您应该使用 NavigableMap 接口,即您将编写一个比较器,将Not-Specified条目放在最后。

Here is an example:

下面是一个例子:

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

Output:

输出:

Last key: Not-Specified, last value: 1

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

Solution using HashMap:

使用HashMap的解决方案:

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

如果您必须依赖 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());

}

Output:

输出:

Last key: Not-Specified, last value: 1

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

回答by u290629

HashMap doesn't have "the last position", as it is not sorted.

HashMap 没有“最后一个位置”,因为它没有排序。

You may use other Mapwhich implements java.util.SortedMap, most popular one is TreeMap.

你可以使用其他的Map实现java.util.SortedMap,最流行的一个是TreeMap

回答by Peter Lawrey

A SortedMapis the logical/best choice, however another option is to use a LinkedHashMapwhich maintains two order modes, most-recently-added goes last, and most-recently-accessed goes last. See the Javadocs for more details.

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

回答by anand

move does not make sense for a hashmap since its a dictionary with a hashcode for bucketing based on key and then a linked list for colliding hashcodes resolved via equals. Use a TreeMap for sorted maps and then pass in a custom comparator.

move 对 hashmap 没有意义,因为它是一个字典,其中包含一个基于键进行分桶的哈希码,然后是一个用于碰撞哈希码的链表,通过 equals 解析。使用 TreeMap 排序映射,然后传入自定义比较器。

回答by Yoshua Nahar

When using numbers as the key, I suppose you could also try this:

当使用数字作为键时,我想你也可以试试这个:

        Map<Long, String> map = new HashMap<>();
        map.put(4L, "The First");
        map.put(6L, "The Second");
        map.put(11L, "The Last");

        long lastKey = 0;
        //you entered Map<Long, String> entry
        for (Map.Entry<Long, String> entry : map.entrySet()) {
            lastKey = entry.getKey();
        }
        System.out.println(lastKey); // 11

回答by Mad Calm

In such scenario last used key is usually known so it can be used for accessing last value (inserted with the one):

在这种情况下,最后使用的密钥通常是已知的,因此它可以用于访问最后一个值(插入一个):

class PostIndexData {
    String _office_name;
    Boolean _isGov;
    public PostIndexData(String name, Boolean gov) {
        _office_name = name;
        _isGov = gov;
    }
}
//-----------------------
class KgpData {
    String _postIndex;
    PostIndexData _postIndexData;
    public KgpData(String postIndex, PostIndexData postIndexData) {
        _postIndex = postIndex;
        _postIndexData = postIndexData;;
    }
}

public class Office2ASMPro {
    private HashMap<String,PostIndexData> _postIndexMap = new HashMap<>();
    private HashMap<String,KgpData> _kgpMap = new HashMap<>();
...
private void addOffice(String kgp, String postIndex, String officeName, Boolean gov) {
            if (_postIndexMap.get(postIndex) == null) {
                _postIndexMap.put(postIndex, new PostIndexData(officeName, gov));
            }
            _kgpMap.put( kgp, new KgpData(postIndex, _postIndexMap.get(postIndex)) );
        }

回答by Muruganandam C

Find missing all elements from array
        int[] array = {3,5,7,8,2,1,32,5,7,9,30,5};
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for(int i=0;i<array.length;i++) {
            map.put(array[i], 1);
        }
        int maxSize = map.lastKey();
        for(int j=0;j<maxSize;j++) {
            if(null == map.get(j))
                System.out.println("Missing `enter code here`No:"+j);
        }