访问地图中的最后一个条目 [英] Accessing the last entry in a Map

查看:150
本文介绍了访问地图中的最后一个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如,我有这样的HashMap值:

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

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

未指定可能会出现在任何位置。它可能会先出现在地图的中间。但我想将未指定移至最后位置。



我该怎么做?感谢提前。

解决方案

用一句话回答你的问题:



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




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

所以你的声明应阅读:

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

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




可能的解决方案



Sorted Maps:



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

您可以通过 lastEntry 方法:

 的NavigableMap<字符串,整数> map = new TreeMap< String,Integer>(); 
//添加一些条目
条目<字符串,整数> lastEntry = map.lastEntry();



链接地图:



LinkedHashMap 的特例,一个HashMap实现它存储键被插入的顺序。然而,没有用于备份此功能的界面,也没有直接访问最后一个键的方法。您只能通过诸如在之间使用List之类的技巧来做到这一点:

  Map< String,String> map = new LinkedHashMap< String,Integer>(); 
//添加一些条目
List< Entry< String,Integer>> entryList = $ b $ new ArrayList< Map.Entry< String,Integer>>(map.entrySet());
条目<字符串,整数> lastEntry =
entryList.get(entryList.size() - 1);



正确的解决方案:



不能控制插入顺序,你应该使用NavigableMap接口,也就是说你可以编写一个比较器来定位未指定的条目。



下面是一个例子:

  final NavigableMap< String,Integer> map = $ b $ 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);
}
返回结果;
}

});
map.put(test,Integer.valueOf(2));
map.put(Not-Specified,Integer.valueOf(1));
map.put(testtest,Integer.valueOf(3));
最终条目<字符串,整数> lastEntry = map.lastEntry();
System.out.println(Last key:+ lastEntry.getKey()
+,last value:+ lastEntry.getValue());

输出:


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



使用HashMap的解决方案:



如果您必须依赖HashMaps,仍然有一个解决方案,使用a)上述比较器的修改版本,b)a 列表已使用地图的 entrySet 和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>>条目=
新ArrayList<条目<字符串,整数>>(map.entrySet());
Collections.sort(entries,new Comparator< Entry< String,Integer>>(){

public int compareKeys(final String o1,final String o2){
int结果;
if(Not-Specified.equals(o1)){
result = 1;
} else if(Not-Specified.equals(o2)){
结果= -1;
}其他{
结果= o1.compareTo(o2);
}
返回结果;
}

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

});

最终条目< String,Integer> lastEntry =
entries.get(entries.size() - 1);
System.out.println(Last key:+ lastEntry.getKey()+,last value:
+ lastEntry.getValue());

$ b

输出:


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


How to move a particular HashMap entry to Last position?

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.

解决方案

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

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

You can access the last entry through the lastEntry method:

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:

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-Specified entry last.

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

Solution using HashMap:

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

}

Output:

Last key: Not-Specified, last value: 1

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

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