java 从 HashMap 中获取第一个和最后一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25742014/
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-11-02 08:35:50  来源:igfitidea点击:

Get first and last element from a HashMap

javahashmap

提问by xm21

I have the following code and I'd like to get able to get the first and last element from the Map and assign each to a String.

我有以下代码,我希望能够从 Map 中获取第一个和最后一个元素并将每个元素分配给一个字符串。

String result1stElement = null;
String resultLastElement = null;

Map<String, String> result = new HashMap<String, String>();
result = myModel.getSampleResults();

Any ideas.

有任何想法吗。

Thanks in advance.

提前致谢。

回答by Sander

First of all, Maps are not ordered so you wont really have a first and last element.

首先,地图不是有序的,所以你不会真的有第一个和最后一个元素。

However, if you wish to get the first and last element of this anyways you could just get the values and convert this into an array. This isn't really pretty, but it'll work.

但是,如果您无论如何都希望获得第一个和最后一个元素,则只需获取值并将其转换为数组即可。这不是很漂亮,但它会起作用。

Map<String, String> result = new HashMap<String, String>();
result = myModel.getSampleResults();
map.values().toArray()[0]; //First result
map.values().toArray()[result.size()-1]; //Last result

Note: This is not tested with a compiler.

注意:这不是用编译器测试的。

回答by Nikolay

First and last element concepts not applicable to Hash-based structures like HashMap and HashSet. Insertion or deletion of key may cause element reordering on-the-fly.

第一个和最后一个元素概念不适用于基于哈希的结构,如 HashMap 和 HashSet。键的插入或删除可能会导致元素即时重新排序。

I guess your model results is an key-value pairs list, not hash map. In this case element ordering is in place. LinkedHashMapkeeps insertion order of elements.

我猜你的模型结果是一个键值对列表,而不是哈希映射。在这种情况下,元素排序就位。LinkedHashMap保持元素的插入顺序。

Replace HashMapto LinkedHashMap(and modify .getSampleResults()) to return LinkedHashMap and check this question for futher details Java LinkedHashMap get first or last entry.

替换HashMapLinkedHashMap(并修改.getSampleResults())以返回 LinkedHashMap 并检查此问题以获取更多详细信息Java LinkedHashMap get first or last entry

回答by biziclop

There is no such a thing as a first and last element in a HashMap. This is the price you have to pay for O(1) lookup: internally the implementation will chuck your entries into a list of buckets in no easily identifiable (but deterministic) order. This process puts the Hashin HashMap, and in fact the more chaotic it is, the better the performance.

a 中没有第一个和最后一个元素这样的东西HashMap。这是您必须为 O(1) 查找付出的代价:在内部,实现会将您的条目以不容易识别(但具有确定性)的顺序放入桶列表中。这个过程把Hashin HashMap,实际上越乱,性能就越好。

You can use a TreeMapif you want a map sorted by the natural order of its keys (or a custom comparator) or you can have a LinkedHashMapif you want the elements to be arranged in the order of insertion.

您可以使用TreeMap,如果你想通过它的键的自然顺序(或自定义的比较)排序的地图,也可以有一个LinkedHashMap,如果你想被安排在插入顺序的元素。

P.s.: even if you choose a Mapimplementation that maintains some kind of order, calling toArray()just to get the first and last elements is a massive overkill, I wouldn't do it. TreeMaphas firstEntry()and lastEntry()methods, and even with LinkedHashMap, it's a lot cheaper to just manually iterate across the elements and keep the first and last one instead of allocating a potentially huge array.

Ps:即使你选择一个Map维护某种顺序的实现,调用toArray()只是为了获取第一个和最后一个元素是一种巨大的矫枉过正,我不会这样做。TreeMaphasfirstEntry()lastEntry()方法,甚至 with LinkedHashMap,手动遍历元素并保留第一个和最后一个元素而不是分配一个潜在的巨大数组要便宜得多。

回答by Arek

HashMap has no such thing as order. From HashMap javadoc:

HashMap 没有顺序这样的东西。从 HashMap javadoc

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

此类不保证地图的顺序;特别是,它不保证订单会随着时间的推移保持不变。

You'll have to use LinkedHashMap. Take a look at entrySet() method and this question+answer

你将不得不使用LinkedHashMap. 看看 entrySet() 方法和这个问题+答案

回答by VdeX

"toArray"method of Set interface can be used.

可以使用 Set 接口的“toArray”方法。

But iterating over the entries in the entry set and getting the first and last entry is a better approach.

但是迭代条目集中的条目并获取第一个和最后一个条目是更好的方法。

This example might be helpful:

这个例子可能会有所帮助:

public static void main(final String[] args) {
        final Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();
        orderMap.put(6, "Six");
        orderMap.put(7, "Seven");
        orderMap.put(3, "Three");
        orderMap.put(100, "Hundered");
        orderMap.put(10, "Ten");

        final Set<Entry<Integer, String>> mapValues = orderMap.entrySet();
        final int maplength = mapValues.size();
        final Entry<Integer,String>[] test = new Entry[maplength];
        mapValues.toArray(test);

        System.out.print("First Key:"+test[0].getKey());
        System.out.println(" First Value:"+test[0].getValue());

        System.out.print("Last Key:"+test[maplength-1].getKey());
        System.out.println(" Last Value:"+test[maplength-1].getValue());
    }

// the output geneated is :
First Key:6 First Value:Six
Last Key:10 Last Value:Ten

回答by codefan-BK

Your comment to @Nikolay's answer shows an important detail of your question that was hidden until now.

您对@Nikolay 的回答的评论显示了您的问题的一个重要细节,该细节直到现在才被隐藏。

So, you want to test a method which uses a HashMapstructure for refering to some added objects and you want to test, if this method delivers some ordering in this structure? First added object shall remain at a "first position", last added object at a "last position"?

因此,您想测试一个方法,该方法使用HashMap结构来引用一些添加的对象,并且您想测试此方法是否在此结构中提供了一些排序?第一个添加的对象应保留在“第一个位置”,最后添加的对象应保留在“最后一个位置”?

As the other answers already show, there is no way without refactoring that method. HashMapdoesn't deliver any meaningful ordering at all and if that method should deliver some ordering, it is simply broken - implementation is faulty.

正如其他答案已经表明的那样,没有重构该方法是不可能的。HashMap根本没有提供任何有意义的排序,如果该方法应该提供一些排序,它只是被破坏了 - 实现是错误的。

Of course, you can write a unit test using the algorithm provided by @Sander. This test will fail most of the time. And this again shows the fact, that the tested method has to be refactured like @Nikolay showed in his answer, for instance.

当然,您可以使用@Sander 提供的算法编写单元测试。大多数情况下,此测试将失败。这再次表明了一个事实,例如,必须像@Nikolay 在他的回答中显示的那样重新构造测试方法。