위치로 HashMap에서 요소를 가져올 수 있습니까?
위치별로 HashMap에서 요소를 검색하는 방법은 무엇입니까?
HashMaps 는 순서를 유지하지 않습니다.
이 클래스는지도의 순서를 보장하지 않습니다. 특히 주문이 시간이 지나도 일정하게 유지된다는 보장은 없습니다.
예측 가능한 반복 순서를 보장하는 LinkedHashMap을 살펴보십시오 .
LinkedHashMap을 사용하고 위치별로 검색해야하는 경우 값을 ArrayList로 변환합니다.
LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<String,String>();
/* Populate */
linkedHashMap.put("key0","value0");
linkedHashMap.put("key1","value1");
linkedHashMap.put("key2","value2");
/* Get by position */
int pos = 1;
String value = (new ArrayList<String>(linkedHashMap.values())).get(pos);
당신은 당신이지도 사용에 요소를 추가하는 순서 유지하려면 LinkedHashMap
단지 반대를 HashMap
.
다음은 맵의 인덱스로 값을 가져올 수있는 접근 방식입니다.
public Object getElementByIndex(LinkedHashMap map,int index){
return map.get( (map.keySet().toArray())[ index ] );
}
어떤 이유로 hashMap을 고수해야한다면 keySet을 배열로 변환하고 배열의 키를 인덱싱하여 다음과 같이 맵에서 값을 가져올 수 있습니다.
Object[] keys = map.keySet().toArray();
그런 다음 다음과 같이지도에 액세스 할 수 있습니다.
map.get(keys[i]);
사용 LinkedHashMap
:
예측 가능한 반복 순서와 함께 Map 인터페이스의 해시 테이블 및 연결 목록 구현. 이 구현은 모든 항목을 통해 실행되는 이중 링크 목록을 유지한다는 점에서 HashMap과 다릅니다.
LinkedHashMap을 사용하고이 함수를 사용하십시오.
private LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
이렇게 정의하고.
private Entry getEntry(int id){
Iterator iterator = map.entrySet().iterator();
int n = 0;
while(iterator.hasNext()){
Entry entry = (Entry) iterator.next();
if(n == id){
return entry;
}
n ++;
}
return null;
}
이 함수는 선택한 항목을 반환 할 수 있습니다.
또 다른 작업 방법은 맵 값을 배열로 변환 한 다음 인덱스에서 요소를 검색하는 것입니다. LinkedHashMap에서 다음 접근 방식을 사용하여 100,000 개의 개체에 대한 인덱스 검색을 통해 100,000 개의 요소를 테스트하면 다음과 같은 결과가 나타납니다.
//My answer:
public Particle getElementByIndex(LinkedHashMap<Point, Particle> map,int index){
return map.values().toArray(new Particle[map.values().size()])[index];
} //68 965 ms
//Syd Lambert's answer:
public Particle getElementByIndex(LinkedHashMap<Point, Particle> map,int index){
return map.get( (map.keySet().toArray())[ index ] );
} //80 700 ms
All in all retrieving element by index from LinkedHashMap seems to be pretty heavy operation.
HashMap - and the underlying data structure - hash tables, do not have a notion of position. Unlike a LinkedList or Vector, the input key is transformed to a 'bucket' where the value is stored. These buckets are not ordered in a way that makes sense outside the HashMap interface and as such, the items you put into the HashMap are not in order in the sense that you would expect with the other data structures
HashMap has no concept of position so there is no way to get an object by position. Objects in Maps are set and get by keys.
I'm assuming by 'position' you're referring to the order in which you've inserted the elements into the HashMap. In that case you want to be using a LinkedHashMap. The LinkedHashMap doesn't offer an accessor method however; you will need to write one like
public Object getElementAt(LinkedHashMap map, int index) {
for (Map.Entry entry : map.entrySet()) {
if (index-- == 0) {
return entry.value();
}
}
return null;
}
HashMaps don't allow access by position, it only knows about the hash code and and it can retrieve the value if it can calculate the hash code of the key. TreeMaps have a notion of ordering. Linkedhas maps preserve the order in which they entered the map.
you can use below code to get key : String [] keys = (String[]) item.keySet().toArray(new String[0]);
and get object or list that insert in HashMap with key of this item like this : item.get(keys[position]);
You can try to implement something like that, look at:
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("juan", 2);
map.put("pedro", 3);
map.put("pablo", 5);
map.put("iphoncio",9)
List<String> indexes = new ArrayList<String>(map.keySet()); // <== Parse
System.out.println(indexes.indexOf("juan")); // ==> 0
System.out.println(indexes.indexOf("iphoncio")); // ==> 3
I hope this works for you.
'code' 카테고리의 다른 글
Node 및 Express 4를 사용한 기본 HTTP 인증 (0) | 2020.09.02 |
---|---|
문자열을 ArrayList로 변환하는 방법은 무엇입니까? (0) | 2020.09.02 |
PostgreSQL에서 중복 레코드 삭제 (0) | 2020.09.02 |
부트 스트랩 선택 드롭 다운 목록 자리 표시 자 (0) | 2020.09.02 |
리퍼러를 사용할 수 없을 때 Ruby on Rails에서 redirect_to : back을 올바르게 수행합니다. (0) | 2020.09.02 |