Java LinkedHashMap获得第一个或最后一个条目。

时间:2022-09-25 15:43:39

I have used LinkedHashMap because it is important the order in which keys entered in the map.

我使用了LinkedHashMap,因为重要的是键在映射中输入的顺序。

But now I want to get the value of key in the first place (the first entered entry) or the last.

但是现在我想要在第一个地方(第一个输入条目)或最后一个地方得到键值。

Should there be a method like first() and last() or something like that?

应该有像first()和last()之类的方法吗?

Do I need to have an iterator to just get the first key entry? That is why I used LinkedHashMap!

我需要一个迭代器才能获得第一个关键条目吗?这就是我使用LinkedHashMap的原因!

Thanks!

谢谢!

11 个解决方案

#1


114  

The semantics of LinkedHashMap are still those of a Map, rather than that of a LinkedList. It retains insertion order, yes, but that's an implementation detail, rather than an aspect of its interface.

LinkedHashMap的语义仍然是Map的语义,而不是LinkedList的语义。它保留了插入顺序,是的,但是这是一个实现细节,而不是接口的一个方面。

The quickest way to get the "first" entry is still entrySet().iterator().next(). Getting the "last" entry is possible, but will entail iterating over the whole entry set by calling .next() until you reach the last. while (iterator.hasNext()) { lastElement = iterator.next() }

获得“第一个”条目的最快方法仍然是entrySet().iterator().next()。获得“最后的”条目是可能的,但是需要遍历整个条目,然后调用.next(),直到到达最后一个。while (iterator.hasNext()) {lastElement = iterator.next()}

edit: However, if you're willing to go beyond the JavaSE API, Apache Commons Collections has its own LinkedMap implementation, which has methods like firstKey and lastKey, which do what you're looking for. The interface is considerably richer.

但是,如果您愿意超越JavaSE API, Apache Commons collection有它自己的LinkedMap实现,它有像firstKey和lastKey这样的方法,它们可以实现您想要的功能。接口相当丰富。

#2


9  

Can you try doing something like (to get the last entry):

你能试着做一些事情吗?

linkedHashMap.entrySet().toArray()[linkedHashMap.size() -1];

it's O(N) :)

这是O(N):)

#3


7  

LinkedHashMap current implementation (Java 8) keeps track of its tail. If performance is a concern and/or the map is large in size, you could access that field via reflection.

LinkedHashMap当前实现(Java 8)跟踪它的尾部。如果性能是一个关注点,并且/或映射的大小很大,您可以通过反射访问该字段。

Because the implementation may change it is probably a good idea to have a fallback strategy too. You may want to log something if an exception is thrown so you know that the implementation has changed.

因为实现可能会改变,所以有一个后备策略也是一个好主意。如果抛出异常,您可能想要记录一些东西,以便您知道实现已经更改。

It could look like:

它可能看起来像:

public static <K, V> Entry<K, V> getFirst(Map<K, V> map) {
  if (map.isEmpty()) return null;
  return map.entrySet().iterator().next();
}

public static <K, V> Entry<K, V> getLast(Map<K, V> map) {
  try {
    if (map instanceof LinkedHashMap) return getLastViaReflection(map);
  } catch (Exception ignore) { }
  return getLastByIterating(map);
}

private static <K, V> Entry<K, V> getLastByIterating(Map<K, V> map) {
  Entry<K, V> last = null;
  for (Entry<K, V> e : map.entrySet()) last = e;
  return last;
}

private static <K, V> Entry<K, V> getLastViaReflection(Map<K, V> map) throws NoSuchFieldException, IllegalAccessException {
  Field tail = map.getClass().getDeclaredField("tail");
  tail.setAccessible(true);
  return (Entry<K, V>) tail.get(map);
}

#4


6  

One more way to get first and last entry of a LinkedHashMap is to use "toArray" method of Set interface.

获得LinkedHashMap的第一个和最后一个条目的另一个方法是使用Set接口的“toArray”方法。

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

但是,我认为迭代条目集中的条目并获得第一个和最后一个条目是一个更好的方法。

The usage of array methods leads to warning of the form " ...needs unchecked conversion to conform to ..." which cannot be fixed [but can be only be suppressed by using the annotation @SuppressWarnings("unchecked")].

数组方法的使用导致了表单的警告“……”需要未经检查的转换以符合…“不能被修复”(但只能通过使用注释@抑制性警告(“未检查”)来抑制)。

Here is a small example to demonstrate the usage of "toArray" method:

这里有一个小示例,演示“toArray”方法的用法:

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

#5


2  

It's a bit dirty, but you can override the removeEldestEntry method of LinkedHashMap, which it might suit you to do as a private anonymous member:

它有点脏,但是您可以覆盖LinkedHashMap的removeEldestEntry方法,它可能适合您作为一个私人匿名成员:

private Splat eldest = null;
private LinkedHashMap<Integer, Splat> pastFutures = new LinkedHashMap<Integer, Splat>() {

    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Splat> eldest) {

        eldest = eldest.getValue();
        return false;
    }
};

So you will always be able to get the first entry at your eldest member. It will be updated every time you perform a put.

因此,你将永远能够得到你的最年长成员的第一个条目。每次你执行一个put,它都会被更新。

It should also be easy to override put and set youngest ...

它也应该易于覆盖和设置最小的…

    @Override
    public Splat put(Integer key, Splat value) {

        youngest = value;
        return super.put(key, value);
    }

It all breaks down when you start removing entries though; haven't figured out a way to kludge that.

当你开始删除条目时,它会崩溃;我还没想出一个办法来解决这个问题。

It's very annoying that you can't otherwise get access to head or tail in a sensible way ...

你无法以一种明智的方式获得头部或尾巴,这是非常恼人的……

#6


2  

I know that I came too late but I would like to offer some alternatives, not something extraordinary but some cases that none mentioned here. In case that someone doesn't care so much for efficiency but he wants something with more simplicity(perhaps find the last entry value with one line of code), all this will get quite simplified with the arrival of Java 8 . I provide some useful scenarios.

我知道我来得太迟了,但我想提供一些替代方案,不是特别的,而是一些没有提到的案例。如果有人不太关心效率,但是他想要更简单的东西(也许用一行代码找到最后一个条目的值),那么随着Java 8的到来,所有这些都将得到简化。我提供了一些有用的场景。

For the sake of the completeness, I compare these alternatives with the solution of arrays that already mentioned in this post by others users. I sum up all the cases and i think they would be useful(when performance does matter or no) especially for new developers, always depends on the matter of each problem

为了完整性起见,我将这些替代方案与其他用户在本文中已经提到的数组的解决方案进行比较。我总结了所有的案例,我认为它们会很有用(当性能很重要的时候),特别是对于新开发人员来说,总是依赖于每个问题的问题。

Possible Alternatives

Usage of Array Method

I took it from the previous answer to to make the follow comparisons. This solution belongs @feresr.

我从之前的答案中得出了下面的比较。这个解决方案属于@feresr。

  public static String FindLasstEntryWithArrayMethod() {
        return String.valueOf(linkedmap.entrySet().toArray()[linkedmap.size() - 1]);
    }

Usage of ArrayList Method

Similar to the first solution with a little bit different performance

类似于第一个解决方案,其性能稍有不同。

public static String FindLasstEntryWithArrayListMethod() {
        List<Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(linkedmap.entrySet());
        return entryList.get(entryList.size() - 1).getValue();
    }

Reduce Method

This method will reduce the set of elements until getting the last element of stream. In addition, it will return only deterministic results

该方法将减少元素集,直到获得流的最后一个元素。此外,它只返回确定性结果。

public static String FindLasstEntryWithReduceMethod() {
        return linkedmap.entrySet().stream().reduce((first, second) -> second).orElse(null).getValue();
    }

SkipFunction Method

This method will get the last element of the stream by simply skipping all the elements before it

该方法将通过跳过之前的所有元素来获得流的最后一个元素。

public static String FindLasstEntryWithSkipFunctionMethod() {
        final long count = linkedmap.entrySet().stream().count();
        return linkedmap.entrySet().stream().skip(count - 1).findFirst().get().getValue();
    }

Iterable Alternative

Iterables.getLast from Google Guava. It has some optimization for Lists and SortedSets too

iterable。从谷歌getLast番石榴。它对列表和排序集也有一些优化。

public static String FindLasstEntryWithGuavaIterable() {
        return Iterables.getLast(linkedmap.entrySet()).getValue();
    }

Here is the full source code

这是完整的源代码。

import com.google.common.collect.Iterables;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class PerformanceTest {

    private static long startTime;
    private static long endTime;
    private static LinkedHashMap<Integer, String> linkedmap;

    public static void main(String[] args) {
        linkedmap = new LinkedHashMap<Integer, String>();

        linkedmap.put(12, "Chaitanya");
        linkedmap.put(2, "Rahul");
        linkedmap.put(7, "Singh");
        linkedmap.put(49, "Ajeet");
        linkedmap.put(76, "Anuj");

        //call a useless action  so that the caching occurs before the jobs starts.
        linkedmap.entrySet().forEach(x -> {});



        startTime = System.nanoTime();
        FindLasstEntryWithArrayListMethod();
        endTime = System.nanoTime();
        System.out.println("FindLasstEntryWithArrayListMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");


         startTime = System.nanoTime();
        FindLasstEntryWithArrayMethod();
        endTime = System.nanoTime();
        System.out.println("FindLasstEntryWithArrayMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.nanoTime();
        FindLasstEntryWithReduceMethod();
        endTime = System.nanoTime();

        System.out.println("FindLasstEntryWithReduceMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.nanoTime();
        FindLasstEntryWithSkipFunctionMethod();
        endTime = System.nanoTime();

        System.out.println("FindLasstEntryWithSkipFunctionMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.currentTimeMillis();
        FindLasstEntryWithGuavaIterable();
        endTime = System.currentTimeMillis();
        System.out.println("FindLasstEntryWithGuavaIterable : " + "took " + (endTime - startTime) + " milliseconds");


    }

    public static String FindLasstEntryWithReduceMethod() {
        return linkedmap.entrySet().stream().reduce((first, second) -> second).orElse(null).getValue();
    }

    public static String FindLasstEntryWithSkipFunctionMethod() {
        final long count = linkedmap.entrySet().stream().count();
        return linkedmap.entrySet().stream().skip(count - 1).findFirst().get().getValue();
    }

    public static String FindLasstEntryWithGuavaIterable() {
        return Iterables.getLast(linkedmap.entrySet()).getValue();
    }

    public static String FindLasstEntryWithArrayListMethod() {
        List<Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(linkedmap.entrySet());
        return entryList.get(entryList.size() - 1).getValue();
    }

    public static String FindLasstEntryWithArrayMethod() {
        return String.valueOf(linkedmap.entrySet().toArray()[linkedmap.size() - 1]);
    }
}

Here is the output with performance of each method

这里是每个方法的输出。

FindLasstEntryWithArrayListMethod : took 0.162 milliseconds
FindLasstEntryWithArrayMethod : took 0.025 milliseconds
FindLasstEntryWithReduceMethod : took 2.776 milliseconds
FindLasstEntryWithSkipFunctionMethod : took 3.396 milliseconds
FindLasstEntryWithGuavaIterable : took 11 milliseconds

#7


1  

I would recommend using ConcurrentSkipListMap which has firstKey() and lastKey() methods

我建议使用具有firstKey()和lastKey()方法的ConcurrentSkipListMap。

#8


1  

Perhaps something like this :

大概是这样的:

LinkedHashMap<Integer, String> myMap;

public String getFirstKey() {
  String out = null;
  for (int key : myMap.keySet()) {
    out = myMap.get(key);
    break;
  }
  return out;
}

public String getLastKey() {
  String out = null;
  for (int key : myMap.keySet()) {
    out = myMap.get(key);
  }
  return out;
}

#9


1  

Suggestion:

建议:

map.remove(map.keySet().iterator().next());

#10


0  

Though linkedHashMap doesn't provide any method to get first, last or any specific object.

虽然linkedHashMap没有提供任何方法来获得第一个、最后一个或任何特定对象。

But its pretty trivial to get :

但它的重要性是:

  • Map orderMap = new LinkedHashMap();
    Set al = orderMap.keySet();
  • Map orderMap = new LinkedHashMap();设置al = orderMap.keySet();

now using iterator on al object ; you can get any object.

现在在al对象上使用迭代器;你可以得到任何物体。

#11


0  

Yea I came across the same problem, but luckily I only need the first element... - This is what I did for it.

是的,我遇到了同样的问题,但幸运的是我只需要第一个元素…-这就是我为它所做的。

private String getDefaultPlayerType()
{
    String defaultPlayerType = "";
    for(LinkedHashMap.Entry<String,Integer> entry : getLeagueByName(currentLeague).getStatisticsOrder().entrySet())
    {
        defaultPlayerType = entry.getKey();
        break;
    }
    return defaultPlayerType;
}

If you need the last element as well - I'd look into how to reverse the order of your map - store it in a temp variable, access the first element in the reversed map(therefore it would be your last element), kill the temp variable.

如果您还需要最后一个元素——我将研究如何反转映射的顺序——将它存储在temp变量中,访问反转映射中的第一个元素(因此它将是您的最后一个元素),从而杀死temp变量。

Here's some good answers on how to reverse order a hashmap:

下面是一些关于如何反转顺序的好答案:

How to iterate hashmap in reverse order in Java

如何在Java中以相反的顺序迭代hashmap ?

If you use help from the above link, please give them up-votes :) Hope this can help someone.

如果你使用以上链接的帮助,请给他们投票:)希望这能帮助别人。

#1


114  

The semantics of LinkedHashMap are still those of a Map, rather than that of a LinkedList. It retains insertion order, yes, but that's an implementation detail, rather than an aspect of its interface.

LinkedHashMap的语义仍然是Map的语义,而不是LinkedList的语义。它保留了插入顺序,是的,但是这是一个实现细节,而不是接口的一个方面。

The quickest way to get the "first" entry is still entrySet().iterator().next(). Getting the "last" entry is possible, but will entail iterating over the whole entry set by calling .next() until you reach the last. while (iterator.hasNext()) { lastElement = iterator.next() }

获得“第一个”条目的最快方法仍然是entrySet().iterator().next()。获得“最后的”条目是可能的,但是需要遍历整个条目,然后调用.next(),直到到达最后一个。while (iterator.hasNext()) {lastElement = iterator.next()}

edit: However, if you're willing to go beyond the JavaSE API, Apache Commons Collections has its own LinkedMap implementation, which has methods like firstKey and lastKey, which do what you're looking for. The interface is considerably richer.

但是,如果您愿意超越JavaSE API, Apache Commons collection有它自己的LinkedMap实现,它有像firstKey和lastKey这样的方法,它们可以实现您想要的功能。接口相当丰富。

#2


9  

Can you try doing something like (to get the last entry):

你能试着做一些事情吗?

linkedHashMap.entrySet().toArray()[linkedHashMap.size() -1];

it's O(N) :)

这是O(N):)

#3


7  

LinkedHashMap current implementation (Java 8) keeps track of its tail. If performance is a concern and/or the map is large in size, you could access that field via reflection.

LinkedHashMap当前实现(Java 8)跟踪它的尾部。如果性能是一个关注点,并且/或映射的大小很大,您可以通过反射访问该字段。

Because the implementation may change it is probably a good idea to have a fallback strategy too. You may want to log something if an exception is thrown so you know that the implementation has changed.

因为实现可能会改变,所以有一个后备策略也是一个好主意。如果抛出异常,您可能想要记录一些东西,以便您知道实现已经更改。

It could look like:

它可能看起来像:

public static <K, V> Entry<K, V> getFirst(Map<K, V> map) {
  if (map.isEmpty()) return null;
  return map.entrySet().iterator().next();
}

public static <K, V> Entry<K, V> getLast(Map<K, V> map) {
  try {
    if (map instanceof LinkedHashMap) return getLastViaReflection(map);
  } catch (Exception ignore) { }
  return getLastByIterating(map);
}

private static <K, V> Entry<K, V> getLastByIterating(Map<K, V> map) {
  Entry<K, V> last = null;
  for (Entry<K, V> e : map.entrySet()) last = e;
  return last;
}

private static <K, V> Entry<K, V> getLastViaReflection(Map<K, V> map) throws NoSuchFieldException, IllegalAccessException {
  Field tail = map.getClass().getDeclaredField("tail");
  tail.setAccessible(true);
  return (Entry<K, V>) tail.get(map);
}

#4


6  

One more way to get first and last entry of a LinkedHashMap is to use "toArray" method of Set interface.

获得LinkedHashMap的第一个和最后一个条目的另一个方法是使用Set接口的“toArray”方法。

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

但是,我认为迭代条目集中的条目并获得第一个和最后一个条目是一个更好的方法。

The usage of array methods leads to warning of the form " ...needs unchecked conversion to conform to ..." which cannot be fixed [but can be only be suppressed by using the annotation @SuppressWarnings("unchecked")].

数组方法的使用导致了表单的警告“……”需要未经检查的转换以符合…“不能被修复”(但只能通过使用注释@抑制性警告(“未检查”)来抑制)。

Here is a small example to demonstrate the usage of "toArray" method:

这里有一个小示例,演示“toArray”方法的用法:

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

#5


2  

It's a bit dirty, but you can override the removeEldestEntry method of LinkedHashMap, which it might suit you to do as a private anonymous member:

它有点脏,但是您可以覆盖LinkedHashMap的removeEldestEntry方法,它可能适合您作为一个私人匿名成员:

private Splat eldest = null;
private LinkedHashMap<Integer, Splat> pastFutures = new LinkedHashMap<Integer, Splat>() {

    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Splat> eldest) {

        eldest = eldest.getValue();
        return false;
    }
};

So you will always be able to get the first entry at your eldest member. It will be updated every time you perform a put.

因此,你将永远能够得到你的最年长成员的第一个条目。每次你执行一个put,它都会被更新。

It should also be easy to override put and set youngest ...

它也应该易于覆盖和设置最小的…

    @Override
    public Splat put(Integer key, Splat value) {

        youngest = value;
        return super.put(key, value);
    }

It all breaks down when you start removing entries though; haven't figured out a way to kludge that.

当你开始删除条目时,它会崩溃;我还没想出一个办法来解决这个问题。

It's very annoying that you can't otherwise get access to head or tail in a sensible way ...

你无法以一种明智的方式获得头部或尾巴,这是非常恼人的……

#6


2  

I know that I came too late but I would like to offer some alternatives, not something extraordinary but some cases that none mentioned here. In case that someone doesn't care so much for efficiency but he wants something with more simplicity(perhaps find the last entry value with one line of code), all this will get quite simplified with the arrival of Java 8 . I provide some useful scenarios.

我知道我来得太迟了,但我想提供一些替代方案,不是特别的,而是一些没有提到的案例。如果有人不太关心效率,但是他想要更简单的东西(也许用一行代码找到最后一个条目的值),那么随着Java 8的到来,所有这些都将得到简化。我提供了一些有用的场景。

For the sake of the completeness, I compare these alternatives with the solution of arrays that already mentioned in this post by others users. I sum up all the cases and i think they would be useful(when performance does matter or no) especially for new developers, always depends on the matter of each problem

为了完整性起见,我将这些替代方案与其他用户在本文中已经提到的数组的解决方案进行比较。我总结了所有的案例,我认为它们会很有用(当性能很重要的时候),特别是对于新开发人员来说,总是依赖于每个问题的问题。

Possible Alternatives

Usage of Array Method

I took it from the previous answer to to make the follow comparisons. This solution belongs @feresr.

我从之前的答案中得出了下面的比较。这个解决方案属于@feresr。

  public static String FindLasstEntryWithArrayMethod() {
        return String.valueOf(linkedmap.entrySet().toArray()[linkedmap.size() - 1]);
    }

Usage of ArrayList Method

Similar to the first solution with a little bit different performance

类似于第一个解决方案,其性能稍有不同。

public static String FindLasstEntryWithArrayListMethod() {
        List<Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(linkedmap.entrySet());
        return entryList.get(entryList.size() - 1).getValue();
    }

Reduce Method

This method will reduce the set of elements until getting the last element of stream. In addition, it will return only deterministic results

该方法将减少元素集,直到获得流的最后一个元素。此外,它只返回确定性结果。

public static String FindLasstEntryWithReduceMethod() {
        return linkedmap.entrySet().stream().reduce((first, second) -> second).orElse(null).getValue();
    }

SkipFunction Method

This method will get the last element of the stream by simply skipping all the elements before it

该方法将通过跳过之前的所有元素来获得流的最后一个元素。

public static String FindLasstEntryWithSkipFunctionMethod() {
        final long count = linkedmap.entrySet().stream().count();
        return linkedmap.entrySet().stream().skip(count - 1).findFirst().get().getValue();
    }

Iterable Alternative

Iterables.getLast from Google Guava. It has some optimization for Lists and SortedSets too

iterable。从谷歌getLast番石榴。它对列表和排序集也有一些优化。

public static String FindLasstEntryWithGuavaIterable() {
        return Iterables.getLast(linkedmap.entrySet()).getValue();
    }

Here is the full source code

这是完整的源代码。

import com.google.common.collect.Iterables;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class PerformanceTest {

    private static long startTime;
    private static long endTime;
    private static LinkedHashMap<Integer, String> linkedmap;

    public static void main(String[] args) {
        linkedmap = new LinkedHashMap<Integer, String>();

        linkedmap.put(12, "Chaitanya");
        linkedmap.put(2, "Rahul");
        linkedmap.put(7, "Singh");
        linkedmap.put(49, "Ajeet");
        linkedmap.put(76, "Anuj");

        //call a useless action  so that the caching occurs before the jobs starts.
        linkedmap.entrySet().forEach(x -> {});



        startTime = System.nanoTime();
        FindLasstEntryWithArrayListMethod();
        endTime = System.nanoTime();
        System.out.println("FindLasstEntryWithArrayListMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");


         startTime = System.nanoTime();
        FindLasstEntryWithArrayMethod();
        endTime = System.nanoTime();
        System.out.println("FindLasstEntryWithArrayMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.nanoTime();
        FindLasstEntryWithReduceMethod();
        endTime = System.nanoTime();

        System.out.println("FindLasstEntryWithReduceMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.nanoTime();
        FindLasstEntryWithSkipFunctionMethod();
        endTime = System.nanoTime();

        System.out.println("FindLasstEntryWithSkipFunctionMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.currentTimeMillis();
        FindLasstEntryWithGuavaIterable();
        endTime = System.currentTimeMillis();
        System.out.println("FindLasstEntryWithGuavaIterable : " + "took " + (endTime - startTime) + " milliseconds");


    }

    public static String FindLasstEntryWithReduceMethod() {
        return linkedmap.entrySet().stream().reduce((first, second) -> second).orElse(null).getValue();
    }

    public static String FindLasstEntryWithSkipFunctionMethod() {
        final long count = linkedmap.entrySet().stream().count();
        return linkedmap.entrySet().stream().skip(count - 1).findFirst().get().getValue();
    }

    public static String FindLasstEntryWithGuavaIterable() {
        return Iterables.getLast(linkedmap.entrySet()).getValue();
    }

    public static String FindLasstEntryWithArrayListMethod() {
        List<Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(linkedmap.entrySet());
        return entryList.get(entryList.size() - 1).getValue();
    }

    public static String FindLasstEntryWithArrayMethod() {
        return String.valueOf(linkedmap.entrySet().toArray()[linkedmap.size() - 1]);
    }
}

Here is the output with performance of each method

这里是每个方法的输出。

FindLasstEntryWithArrayListMethod : took 0.162 milliseconds
FindLasstEntryWithArrayMethod : took 0.025 milliseconds
FindLasstEntryWithReduceMethod : took 2.776 milliseconds
FindLasstEntryWithSkipFunctionMethod : took 3.396 milliseconds
FindLasstEntryWithGuavaIterable : took 11 milliseconds

#7


1  

I would recommend using ConcurrentSkipListMap which has firstKey() and lastKey() methods

我建议使用具有firstKey()和lastKey()方法的ConcurrentSkipListMap。

#8


1  

Perhaps something like this :

大概是这样的:

LinkedHashMap<Integer, String> myMap;

public String getFirstKey() {
  String out = null;
  for (int key : myMap.keySet()) {
    out = myMap.get(key);
    break;
  }
  return out;
}

public String getLastKey() {
  String out = null;
  for (int key : myMap.keySet()) {
    out = myMap.get(key);
  }
  return out;
}

#9


1  

Suggestion:

建议:

map.remove(map.keySet().iterator().next());

#10


0  

Though linkedHashMap doesn't provide any method to get first, last or any specific object.

虽然linkedHashMap没有提供任何方法来获得第一个、最后一个或任何特定对象。

But its pretty trivial to get :

但它的重要性是:

  • Map orderMap = new LinkedHashMap();
    Set al = orderMap.keySet();
  • Map orderMap = new LinkedHashMap();设置al = orderMap.keySet();

now using iterator on al object ; you can get any object.

现在在al对象上使用迭代器;你可以得到任何物体。

#11


0  

Yea I came across the same problem, but luckily I only need the first element... - This is what I did for it.

是的,我遇到了同样的问题,但幸运的是我只需要第一个元素…-这就是我为它所做的。

private String getDefaultPlayerType()
{
    String defaultPlayerType = "";
    for(LinkedHashMap.Entry<String,Integer> entry : getLeagueByName(currentLeague).getStatisticsOrder().entrySet())
    {
        defaultPlayerType = entry.getKey();
        break;
    }
    return defaultPlayerType;
}

If you need the last element as well - I'd look into how to reverse the order of your map - store it in a temp variable, access the first element in the reversed map(therefore it would be your last element), kill the temp variable.

如果您还需要最后一个元素——我将研究如何反转映射的顺序——将它存储在temp变量中,访问反转映射中的第一个元素(因此它将是您的最后一个元素),从而杀死temp变量。

Here's some good answers on how to reverse order a hashmap:

下面是一些关于如何反转顺序的好答案:

How to iterate hashmap in reverse order in Java

如何在Java中以相反的顺序迭代hashmap ?

If you use help from the above link, please give them up-votes :) Hope this can help someone.

如果你使用以上链接的帮助,请给他们投票:)希望这能帮助别人。