HashMap : 하나의 키, 여러 값
이 맵의 첫 번째 키에 대한 세 번째 값을 어떻게 얻을 수 있습니까? 이것이 가능한가?
이를 수행하기 위해 라이브러리가 존재하지만 가장 간단한 Java 방법은 다음 Map
과 List
같이 만드는 것 입니다 .
Map<Object,ArrayList<Object>> multiMap = new HashMap<>();
멀티 맵을 찾고있는 것 같습니다 . Guava 에는 Multimap
일반적으로 Multimaps
클래스 를 통해 생성되는 다양한 구현이 있습니다.
나는 그 구현을 사용하는 것이 자신의 것을 롤링하는 것보다 더 간단 할 수 있다고 제안하고, API가 어떻게 생겼는지 알아 내고, 값을 추가 할 때 기존 목록을주의 깊게 확인하는 등의 작업을합니다. 상황이 타사 라이브러리에 대한 특정 혐오감을 가지고 있다면 그것은 그럴만 한 가치가 있지만 그렇지 않으면 Guava는 아마도 다른 코드에서도 도움이 될 멋진 라이브러리입니다. :)
예를 들면 :
Map<Object,Pair<Integer,String>> multiMap = new HashMap<Object,Pair<Integer,String>>();
어디 Pair
파라 메트릭 클래스입니다
public class Pair<A, B> {
A first = null;
B second = null;
Pair(A first, B second) {
this.first = first;
this.second = second;
}
public A getFirst() {
return first;
}
public void setFirst(A first) {
this.first = first;
}
public B getSecond() {
return second;
}
public void setSecond(B second) {
this.second = second;
}
}
Map<String, List<String>> hm = new HashMap<String, List<String>>();
List<String> values = new ArrayList<String>();
values.add("Value 1");
values.add("Value 2");
hm.put("Key1", values);
// to get the arraylist
System.out.println(hm.get("key1"));
결과 : [값 1, 값 2]
이런거있어?
HashMap<String, ArrayList<String>>
그렇다면 ArrayList를 반복하고 arrayList.get (i)로 원하는 항목을 가져올 수 있습니다.
표준 Java HashMap은 키당 여러 값을 저장할 수 없으며 추가 한 새 항목은 이전 항목을 덮어 씁니다.
컬렉션을 사용하여 키 값을 저장해보세요.
Map<Key, Collection<Value>>
가치 목록을 직접 유지해야합니다.
무작위 검색에 대한 블로그를 찾았습니다. 이것이 도움이 될 것이라고 생각합니다. http://tomjefferys.blogspot.com.tr/2011/09/multimaps-google-guava.html
public class MutliMapTest {
public static void main(String... args) {
Multimap<String, String> myMultimap = ArrayListMultimap.create();
// Adding some key/value
myMultimap.put("Fruits", "Bannana");
myMultimap.put("Fruits", "Apple");
myMultimap.put("Fruits", "Pear");
myMultimap.put("Vegetables", "Carrot");
// Getting the size
int size = myMultimap.size();
System.out.println(size); // 4
// Getting values
Collection<String> fruits = myMultimap.get("Fruits");
System.out.println(fruits); // [Bannana, Apple, Pear]
Collection<string> vegetables = myMultimap.get("Vegetables");
System.out.println(vegetables); // [Carrot]
// Iterating over entire Mutlimap
for(String value : myMultimap.values()) {
System.out.println(value);
}
// Removing a single value
myMultimap.remove("Fruits","Pear");
System.out.println(myMultimap.get("Fruits")); // [Bannana, Pear]
// Remove all values for a key
myMultimap.removeAll("Fruits");
System.out.println(myMultimap.get("Fruits")); // [] (Empty Collection!)
}
}
2 개의 키가있는 Map에 대해 생각하면 즉시 사용자 정의 키를 사용하게되었고 아마도 Class 일 것입니다. 다음은 주요 클래스입니다.
public class MapKey {
private Object key1;
private Object key2;
public Object getKey1() {
return key1;
}
public void setKey1(Object key1) {
this.key1 = key1;
}
public Object getKey2() {
return key2;
}
public void setKey2(Object key2) {
this.key2 = key2;
}
}
// Create first map entry with key <A,B>.
MapKey mapKey1 = new MapKey();
mapKey1.setKey1("A");
mapKey1.setKey2("B");
HashMap – 목록을 사용한 단일 키 및 다중 값
Map<String, List<String>> map = new HashMap<String, List<String>>();
// create list one and store values
List<String> One = new ArrayList<String>();
One.add("Apple");
One.add("Aeroplane");
// create list two and store values
List<String> Two = new ArrayList<String>();
Two.add("Bat");
Two.add("Banana");
// put values into map
map.put("A", One);
map.put("B", Two);
map.put("C", Three);
You can do something like this (add access modifiers as required):
Map<String,Map<String,String>> complexMap=new HashMap<String,Map<String,String>>();
You can insert data like this:
Map<String,String> componentMap = new HashMap<String,String>();
componentMap.put("foo","bar");
componentMap.put("secondFoo","secondBar");
complexMap.put("superFoo",componentMap);
The Generated Data Structure would be:
{superFoo={secondFoo=secondBar, foo=bar}}
This way each value for the key should have a unique identifier. Also gives O(1) for fetches,if keys are known.
Write a new class that holds all the values that you need and use the new class's object as the value in your HashMap
HashMap<String, MyObject>
class MyObject {
public String value1;
public int value2;
public List<String> value3;
}
Here is the code how to get extract the hashmap into arrays, hashmap that contains arraylist
Map<String, List<String>> country_hashmap = new HashMap<String, List<String>>();
List<String> my = new ArrayList<String>();
arraylist.add("16873538.webp");
arraylist.add("16873539.webp");
country_hashmap.put("Malaysia", my);
// make another one
List<String> jpn = new ArrayList<String>();
soraru.add("16873540.webp");
soraru.add("16873541.webp");
country_hashmap.put("Japanese", jpn);
for(Map.Entry<String, List<String>> hashmap_data : country_hashmap.entrySet()){
String key = hashmap_data.getKey(); // contains the keys
List<String> val = hashmap_data.getValue(); // contains arraylists
// print all the key and values in the hashmap
System.out.println(key + ": " +val);
// using interator to get the specific values arraylists
Iterator<String> itr = val.iterator();
int i = 0;
String[] data = new String[val.size()];
while (itr.hasNext()){
String array = itr.next();
data[i] = array;
System.out.println(data[i]); // GET THE VALUE
i++;
}
}
참고URL : https://stackoverflow.com/questions/8229473/hashmap-one-key-multiple-values
'Nice programing' 카테고리의 다른 글
What does 'extended' mean in express 4.0? (0) | 2020.11.16 |
---|---|
iPhone없이 Apple 푸시 알림 서비스를 테스트하려면 어떻게해야합니까? (0) | 2020.11.16 |
Collections.synchronizedList 및 동기화 됨 (0) | 2020.11.16 |
printStackTrace (); 피하십시오. (0) | 2020.11.16 |
Visual Studio는 수정되지 않은 프로젝트를 다시 빌드합니다. (0) | 2020.11.16 |