programing

동일한 키 아래에 여러 값이 있는 HashMap

copyandpastes 2022. 8. 3. 23:44
반응형

동일한 키 아래에 여러 값이 있는 HashMap

1개의 키와 2개의 값으로 HashMap을 구현할 수 있습니까?HashMap처럼요?

또, 3개의 가치의 스토리지를 실장할 수 있는 다른 방법(방법이 없는 경우)을 가르쳐 주세요.

다음과 같은 것이 있습니다.

  1. 이치노 Map<KeyType, List<ValueType>>.
  2. 새 래퍼 클래스를 만들고 이 래퍼의 인스턴스를 맵에 배치합니다. Map<KeyType, WrapperType>.
  3. tuple like 클래스를 사용합니다(많은 래퍼를 생성할 필요가 없습니다). Map<KeyType, Tuple<Value1Type, Value2Type>>.
  4. 여러 지도를 나란히 사용하세요.

1. 리스트를 값으로 한 맵

// create our map
Map<String, List<Person>> peopleByForename = new HashMap<>();    

// populate it
List<Person> people = new ArrayList<>();
people.add(new Person("Bob Smith"));
people.add(new Person("Bob Jones"));
peopleByForename.put("Bob", people);

// read from it
List<Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs[0];
Person bob2 = bobs[1];

이 접근방식의 단점은 리스트가 정확히2개의 값에 구속되지 않는다는 것입니다.

2. 래퍼 클래스의 사용

// define our wrapper
class Wrapper {
    public Wrapper(Person person1, Person person2) {
       this.person1 = person1;
       this.person2 = person2;
    }

    public Person getPerson1 { return this.person1; }
    public Person getPerson2 { return this.person2; }

    private Person person1;
    private Person person2;
}

// create our map
Map<String, Wrapper> peopleByForename = new HashMap<>();

// populate it
peopleByForename.put("Bob", new Wrapper(new Person("Bob Smith"),
                                        new Person("Bob Jones"));

// read from it
Wrapper bobs = peopleByForename.get("Bob");
Person bob1 = bobs.getPerson1;
Person bob2 = bobs.getPerson2;

이 접근법의 단점은 이러한 매우 단순한 컨테이너 클래스에 대해 많은 보일러 플레이트 코드를 작성해야 한다는 것입니다.

3. 태플 사용

// you'll have to write or download a Tuple class in Java, (.NET ships with one)

// create our map
Map<String, Tuple2<Person, Person> peopleByForename = new HashMap<>();

// populate it
peopleByForename.put("Bob", new Tuple2(new Person("Bob Smith",
                                       new Person("Bob Jones"));

// read from it
Tuple<Person, Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs.Item1;
Person bob2 = bobs.Item2;

내 생각에 이것이 최선의 해결책이다.

4. 다중 지도

// create our maps
Map<String, Person> firstPersonByForename = new HashMap<>();
Map<String, Person> secondPersonByForename = new HashMap<>();

// populate them
firstPersonByForename.put("Bob", new Person("Bob Smith"));
secondPersonByForename.put("Bob", new Person("Bob Jones"));

// read from them
Person bob1 = firstPersonByForename["Bob"];
Person bob2 = secondPersonByForename["Bob"];

이 솔루션의 단점은 두 맵이 관련이 있는지 명확하지 않다는 것입니다. 프로그램 오류로 인해 두 맵이 동기화되지 않을 수 있습니다.

아니요, 단순히HashMapneed본 . . . . .가 필요합니다HashMap키에서 값 집합으로 이동합니다.

외부 라이브러리를 사용하는 것이 만족스러운 경우, Guava는 , 등의 구현에 정확히 이 개념을 가지고 있습니다.

Multimap<String, Integer> nameToNumbers = HashMultimap.create();

System.out.println(nameToNumbers.put("Ann", 5)); // true
System.out.println(nameToNumbers.put("Ann", 5)); // false
nameToNumbers.put("Ann", 6);
nameToNumbers.put("Sam", 7);

System.out.println(nameToNumbers.size()); // 3
System.out.println(nameToNumbers.keySet().size()); // 2

Apache Commons의 MultiValueMap을 사용하는 것도 좋은 선택입니다.페이지 상단에 있는 All Known Implementing Classes(모든 기존 구현 클래스)를 참조하십시오.

예:

HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()

로 대체될 수 있다

MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();

그렇게,

map.put(key, "A");
map.put(key, "B");
map.put(key, "C");

Collection<String> coll = map.get(key);

.coll "및 "를 합니다.A", "B" "C" 입니다.

, 그럼 ㄴㄴㄴ데를 한 번 보세요.Multimapguava와 그 구현으로부터 -

Map과 비슷하지만 여러 값을 하나의 키에 연결할 수 있습니다.put(K, V)을 2회 호출한 경우 키는 같지만 값은 다릅니다.멀티맵에는 키에서 두 값에 대한 매핑이 포함됩니다.

용 i i i i를 쓴다.Map<KeyType, Object[]>이치이렇게 하면 키와 관련된 여러 유형의 값을 저장할 수 있습니다.Object []에서 삽입 및 검색 순서를 적절하게 유지해야 합니다.

예:학생 정보를 저장하려고 합니다.키는 id이며, 이름과 주소, 그리고 학생에 관련된 이메일을 저장하려고 합니다.

       //To make entry into Map
        Map<Integer, String[]> studenMap = new HashMap<Integer, String[]>();
        String[] studentInformationArray = new String[]{"name", "address", "email"};
        int studenId = 1;
        studenMap.put(studenId, studentInformationArray);

        //To retrieve values from Map
        String name = studenMap.get(studenId)[1];
        String address = studenMap.get(studenId)[2];
        String email = studenMap.get(studenId)[3];
HashMap<Integer,ArrayList<String>> map = new    HashMap<Integer,ArrayList<String>>();

ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("xyz");
map.put(100,list);

Spring Framework를 사용하는 경우.다음과 같은 것이 있습니다.org.springframework.util.MultiValueMap.

수정할 수 없는 다중값 맵을 작성하려면:

Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);

「」를 사용합니다.org.springframework.util.LinkedMultiValueMap

은 'JDK8'을 하는 것입니다.Map::compute★★★★

map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);

예를 들어

public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();

    put(map, "first", "hello");
    put(map, "first", "foo");
    put(map, "bar", "foo");
    put(map, "first", "hello");

    map.forEach((s, strings) -> {
        System.out.print(s + ": ");
        System.out.println(strings.stream().collect(Collectors.joining(", ")));
    });
}

private static <KEY, VALUE> void put(Map<KEY, List<VALUE>> map, KEY key, VALUE value) {
    map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);
}

출력:

bar: foo
first: hello, foo, hello

가 이 구조에 했을 , 「 」는 「 」라고 하는 점에 주의해 주세요.ConcurrentHashMap ★★★★★★★★★★★★★★★★★」CopyOnWriteArrayList예를 들어 사용할 필요가 있습니다.

가장 쉬운 방법은 Google 컬렉션 라이브러리를 사용하는 것입니다.

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Test {

    public static void main(final String[] args) {

        // multimap can handle one key with a list of values
        final Multimap<String, String> cars = ArrayListMultimap.create();
        cars.put("Nissan", "Qashqai");
        cars.put("Nissan", "Juke");
        cars.put("Bmw", "M3");
        cars.put("Bmw", "330E");
        cars.put("Bmw", "X6");
        cars.put("Bmw", "X5");

        cars.get("Bmw").forEach(System.out::println);

        // It will print the:
        // M3
        // 330E
        // X6
        // X5
    }

}

maven 링크: https://mvnrepository.com/artifact/com.google.collections/google-collections/1.0-rc2

자세한 것은, http://tomjefferys.blogspot.be/2011/09/multimaps-google-guava.html 를 참조해 주세요.

한마디로 이야기할 수 없군요.해결책은 키에 대응하는 2(3개 이상의) 값을 포함하는 값에 대한 Wrapper Clas를 작성하는 것입니다.

이것은 '아, 아, 아, 아, 아, 아이다'라고 .multimap.

참조: http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/Multimap.html

Java Collector 사용

// Group employees by department
Map<Department, List<Employee>> byDept = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getDepartment));

여기서 Department는 키입니다.

String key= "services_servicename"

ArrayList<String> data;

for(int i = 0; i lessthen data.size(); i++) {
    HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
    servicesNameHashmap.put(key,data.get(i).getServiceName());
    mServiceNameArray.add(i,servicesNameHashmap);
}

나는 최고의 결과를 얻었다.

새로 돼요.HashMap

HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();

안에서for같은 키와 여러 개의 값처럼 같은 효과를 얻을 수 있습니다.

 import java.io.*;
 import java.util.*;

 import com.google.common.collect.*;

 class finTech{
public static void main(String args[]){
       Multimap<String, String> multimap = ArrayListMultimap.create();
       multimap.put("1","11");
       multimap.put("1","14");
       multimap.put("1","12");
       multimap.put("1","13");
       multimap.put("11","111");
       multimap.put("12","121");
        System.out.println(multimap);
        System.out.println(multimap.get("11"));
   }                                                                                            
 }                                                                    

출력:

     {"1"=["11","12","13","14"],"11"=["111"],"12"=["121"]}

      ["111"]

유틸리티 기능을 위한 Google-Guava 라이브러리입니다.이것이 필요한 해결책입니다.

Paul의 코멘트에 대한 답변을 올릴 수 없었기 때문에 Vidhya를 위해 여기에 새로운 코멘트를 작성합니다.

는 퍼음음음음음 a a a a a이다.SuperClass값으로 저장하려는 두 클래스에 대해 설명합니다.

래퍼 클래스 내에서는 어소시에이션을 2개의 클래스 객체의 인스턴스 변수 객체로 배치할 수 있습니다.

예.

class MyWrapper {

 Class1 class1obj = new Class1();
 Class2 class2obj = new Class2();
...
}

HashMap에는 이렇게 입력할 수 있습니다.

Map<KeyObject, WrapperObject> 

WrapperObj에는 클래스 변수가 있습니다.class1Obj, class2Obj

넌 암묵적으로 할 수 있어.

// Create the map. There is no restriction to the size that the array String can have
HashMap<Integer, String[]> map = new HashMap<Integer, String[]>();

//initialize a key chosing the array of String you want for your values
map.put(1, new String[] { "name1", "name2" });

//edit value of a key
map.get(1)[0] = "othername";

이것은 매우 간단하고 효과적입니다.대신 다른 클래스의 값을 원하는 경우 다음을 수행할 수 있습니다.

HashMap<Integer, Object[]> map = new HashMap<Integer, Object[]>();

identityHashMap을 사용하여 수행할 수 있으며, 키 비교는 == 연산자에 의해 수행되며 동일하지 않다는 조건이 적용됩니다.

별도의 클래스를 만들지 않고 변수를 몇 개라도 저장하기 위해 다음을 선호합니다.

final public static Map<String, Map<String, Float>> myMap    = new HashMap<String, Map<String, Float>>();

목표 C에 있는 데이터 사전을 사용하여 이 작업을 수행하는 데 너무 익숙합니다.안드로이드용 자바에서는 비슷한 결과를 얻기 어려웠다.커스텀 클래스를 만들고 커스텀 클래스의 해시 맵을 작성했습니다.

public class Test1 {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addview);

//create the datastring
    HashMap<Integer, myClass> hm = new HashMap<Integer, myClass>();
    hm.put(1, new myClass("Car", "Small", 3000));
    hm.put(2, new myClass("Truck", "Large", 4000));
    hm.put(3, new myClass("Motorcycle", "Small", 1000));

//pull the datastring back for a specific item.
//also can edit the data using the set methods.  this just shows getting it for display.
    myClass test1 = hm.get(1);
    String testitem = test1.getItem();
    int testprice = test1.getPrice();
    Log.i("Class Info Example",testitem+Integer.toString(testprice));
}
}

//custom class.  You could make it public to use on several activities, or just include in the activity if using only here
class myClass{
    private String item;
    private String type;
    private int price;

    public myClass(String itm, String ty, int pr){
        this.item = itm;
        this.price = pr;
        this.type = ty;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public String getType() {
        return item;
    }

    public void setType(String type) {
        this.type = type;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

}

여러 키 또는 값을 가지도록 클래스를 만들고 이 클래스의 개체를 맵의 매개 변수로 사용할 수 있습니다.https://stackoverflow.com/a/44181931/8065321 를 참조해 주세요.

Apache Commons 컬렉션 클래스는 동일한 키로 여러 값을 구현할 수 있습니다.

MultiMap multiMapDemo = new MultiValueMap();

multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");

System.out.println(multiMapDemo.get("fruit"));

메이븐 의존 관계

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-collections4</artifactId>
   <version>4.4</version>
</dependency>

언급URL : https://stackoverflow.com/questions/4956844/hashmap-with-multiple-values-under-the-same-key

반응형