Java LinkedHashMap은 첫 번째 또는 마지막 항목을 얻습니다.
LinkedHashMap지도에 키를 입력 한 순서가 중요하기 때문에 사용 했습니다.
그러나 이제 첫 번째 (첫 번째 입력 한 항목) 또는 마지막에서 키의 가치를 얻고 싶습니다.
유사한 방법이 있어야 first()하고 last()그런이나 뭐?
첫 번째 키 항목을 얻으려면 반복자가 필요합니까? 그래서 내가 사용한 이유입니다 LinkedHashMap!
감사!
의 의미 LinkedHashMap는 여전히 의 의미가 아니라지도 의 의미입니다 LinkedList. 삽입 순서는 유지되지만 인터페이스의 측면이 아니라 구현 세부 사항입니다.
"첫 번째"항목을 얻는 가장 빠른 방법은 여전히 entrySet().iterator().next()입니다. "마지막"항목을 얻는 것은 가능하지만 마지막 항목에 .next()도달 할 때까지 전화를 걸어 전체 항목 세트를 반복 해야합니다.while (iterator.hasNext()) { lastElement = iterator.next() }
편집 : 그러나 JavaSE API를 넘어서고 싶다면 Apache Commons Collections 에는 자체 LinkedMap구현이 있으며,이 메소드에는 firstKeyand와 같은 메소드가 있으며 원하는 lastKey것을 수행합니다. 인터페이스가 훨씬 풍부합니다.
마지막 항목을 얻기 위해 다음과 같은 작업을 시도 할 수 있습니까?
linkedHashMap.entrySet().toArray()[linkedHashMap.size() -1];
켜졌 어) :)
나는 너무 늦었다는 것을 알고 있지만 특별한 것이 아니라 여기에 언급되지 않은 일부 대안을 제시하고 싶습니다. 누군가가 효율성을별로 신경 쓰지 않지만 더 단순하게 무언가를 원한다면 (아마도 한 줄의 코드로 마지막 항목 값을 찾으십시오), Java 8 이 도착하면이 모든 것이 상당히 단순화됩니다 . 유용한 시나리오를 제공합니다.
완벽을 기하기 위해이 대안을 다른 사용자가이 게시물에서 이미 언급 한 어레이 솔루션과 비교합니다. 나는 모든 경우를 요약하고 특히 새로운 개발자에게 유용 할 것이라고 생각합니다 (성능이 중요하거나 아예 없을 때), 항상 각 문제의 문제에 달려 있습니다
가능한 대안
배열 방법의 사용법
이전 답변에서 추후 비교를하기 위해 가져 왔습니다. 이 솔루션은 @feresr에 속해 있습니다.
public static String FindLasstEntryWithArrayMethod() {
return String.valueOf(linkedmap.entrySet().toArray()[linkedmap.size() - 1]);
}
ArrayList 메서드의 사용법
약간 다른 성능을 가진 첫 번째 솔루션과 유사
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 FindLasstEntryWithReduceMethod() {
return linkedmap.entrySet().stream().reduce((first, second) -> second).orElse(null).getValue();
}
SkipFunction 방법
이 메소드는 단순히 모든 요소를 건너 뛰어 스트림의 마지막 요소를 가져옵니다.
public static String FindLasstEntryWithSkipFunctionMethod() {
final long count = linkedmap.entrySet().stream().count();
return linkedmap.entrySet().stream().skip(count - 1).findFirst().get().getValue();
}
반복 가능한 대안
Google 구아바에서 Iterables.getLast. Lists 및 SortedSets에 대한 최적화도 있습니다.
public static String FindLasstEntryWithGuavaIterable() {
return Iterables.getLast(linkedmap.entrySet()).getValue();
}
전체 소스 코드는 다음과 같습니다
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]);
}
}
다음은 각 방법의 성능을 보여주는 출력입니다
FindLasstEntryWithArrayListMethod : took 0.162 milliseconds
FindLasstEntryWithArrayMethod : took 0.025 milliseconds
FindLasstEntryWithReduceMethod : took 2.776 milliseconds
FindLasstEntryWithSkipFunctionMethod : took 3.396 milliseconds
FindLasstEntryWithGuavaIterable : took 11 milliseconds
LinkedHashMap현재 구현 (자바 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);
}
One more way to get first and last entry of a LinkedHashMap is to use "toArray" method of Set interface.
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:
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
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:
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.
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 ...
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;
}
I would recommend using ConcurrentSkipListMap which has firstKey() and lastKey() methods
Suggestion:
map.remove(map.keySet().iterator().next());
Though linkedHashMap doesn't provide any method to get first, last or any specific object.
But its pretty trivial to get :
- Map orderMap = new LinkedHashMap();
Set al = orderMap.keySet();
now using iterator on al object ; you can get any object.
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.
Here's some good answers on how to reverse order a hashmap:
How to iterate hashmap in reverse order in Java
If you use help from the above link, please give them up-votes :) Hope this can help someone.
right, you have to manually enumerate keyset till the end of the linkedlist, then retrieve the entry by key and return this entry.
참고URL : https://stackoverflow.com/questions/1936462/java-linkedhashmap-get-first-or-last-entry
'Programing' 카테고리의 다른 글
| Keras binary_crossentropy 대 categorical_crossentropy 성능? (0) | 2020.07.15 |
|---|---|
| 스케일링시 보간 비활성화 (0) | 2020.07.14 |
| C #에서 ToUpper ()와 ToUpperInvariant ()의 차이점은 무엇입니까? (0) | 2020.07.14 |
| PostgreSQL DB에서 현재 연결 수를 가져 오는 올바른 쿼리 (0) | 2020.07.14 |
| 파이썬의 목적 __repr__ (0) | 2020.07.14 |