Programming

하나의 명령문에서 한 번에 여러 항목을 HashMap에 추가

procodes 2020. 7. 16. 20:04
반응형

하나의 명령문에서 한 번에 여러 항목을 HashMap에 추가


상수 HashMap을 초기화하고 한 줄로 수행하고 싶습니다. 이 같은 sth를 피하십시오 :

  hashMap.put("One", new Integer(1)); // adding value into HashMap
  hashMap.put("Two", new Integer(2));      
  hashMap.put("Three", new Integer(3));

목표 C에서 이와 유사합니다.

[NSDictionary dictionaryWithObjectsAndKeys:
@"w",[NSNumber numberWithInt:1],
@"K",[NSNumber numberWithInt:2],
@"e",[NSNumber numberWithInt:4],
@"z",[NSNumber numberWithInt:5],
@"l",[NSNumber numberWithInt:6],
nil] 

나는 그렇게 많은 것을 보았을 때 이것을하는 방법을 보여주는 예를 찾지 못했습니다.


당신은 이것을 할 수 있습니다 :

Map<String, Integer> hashMap = new HashMap<String, Integer>()
{{
     put("One", 1);
     put("Two", 2);
     put("Three", 3);
}};

Google Guava의 ImmutableMap을 사용할 수 있습니다. 나중에 맵 수정에 신경 쓰지 않는 한 작동합니다 (이 메소드를 사용하여 맵을 생성 한 후 맵에서 .put ()을 호출 할 수 없음).

import com.google.common.collect.ImmutableMap;

// For up to five entries, use .of()
Map<String, Integer> littleMap = ImmutableMap.of(
    "One", Integer.valueOf(1),
    "Two", Integer.valueOf(2),
    "Three", Integer.valueOf(3)
);

// For more than five entries, use .builder()
Map<String, Integer> bigMap = ImmutableMap.<String, Integer>builder()
    .put("One", Integer.valueOf(1))
    .put("Two", Integer.valueOf(2))
    .put("Three", Integer.valueOf(3))
    .put("Four", Integer.valueOf(4))
    .put("Five", Integer.valueOf(5))
    .put("Six", Integer.valueOf(6))
    .build();

참조 : http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.html

다소 관련된 질문 : 지도의 HashMap에 대한 ImmutableMap.of () 해결 방법?


Java 9부터는 Map.of(...)다음과 같이 사용할 수 있습니다.

Map<String, Integer> immutableMap = Map.of("One", 1, 
                                           "Two", 2, 
                                           "Three", 3);

이지도는 변경할 수 없습니다. 맵을 변경하려면 다음을 추가해야합니다.

Map<String, Integer> hashMap = new HashMap<>(immutableMap);

Java 9를 사용할 수 없다면 비슷한 도우미 메서드를 직접 작성하거나 Guava 와 같은 타사 라이브러리를 사용하여 해당 기능을 추가해야합니다.


Java에는 맵 리터럴이 없으므로 원하는 것을 정확하게 수행하는 좋은 방법이 없습니다.

해당 유형의 구문이 필요한 경우 Java와 호환되고 다음을 수행 할 수있는 Groovy를 고려하십시오.

def map = [name:"Gromit", likes:"cheese", id:1234]

지도에는 Java 9에 팩토리 메소드가 추가되었습니다. 최대 10 개의 항목에 대해 키와 값 쌍을 취하는 생성자가 오버로드되었습니다. 예를 들어 다음과 같이 다양한 도시와 인구 (2016 년 10 월 Google에 따라)의지도를 작성할 수 있습니다.

Map<String, Integer> cities = Map.of("Brussels", 1_139000, "Cardiff", 341_000);

The var-args case for Map is a little bit harder, you need to have both keys and values, but in Java, methods can’t have two var-args parameters. So the general case is handled by taking a var-args method of Map.Entry<K, V> objects and adding a static entry() method that constructs them. For example:

Map<String, Integer> cities = Map.ofEntries(
    entry("Brussels", 1139000), 
    entry("Cardiff", 341000)
);

Collection Factory Methods in Java 9


Here's a simple class that will accomplish what you want

import java.util.HashMap;

public class QuickHash extends HashMap<String,String> {
    public QuickHash(String...KeyValuePairs) {
        super(KeyValuePairs.length/2);
        for(int i=0;i<KeyValuePairs.length;i+=2)
            put(KeyValuePairs[i], KeyValuePairs[i+1]);
    }
}

And then to use it

Map<String, String> Foo=QuickHash(
    "a", "1",
    "b", "2"
);

This yields {a:1, b:2}


    boolean x;
    for (x = false, 
        map.put("One", new Integer(1)), 
        map.put("Two", new Integer(2)),      
        map.put("Three", new Integer(3)); x;);

Ignoring the declaration of x (which is necessary to avoid an "unreachable statement" diagnostic), technically it's only one statement.


You could add this utility function to a utility class:

public static <K, V> Map<K, V> mapOf(Object... keyValues) {
    Map<K, V> map = new HashMap<>();

    for (int index = 0; index < keyValues.length / 2; index++) {
        map.put((K)keyValues[index * 2], (V)keyValues[index * 2 + 1]);
    }

    return map;
}

Map<Integer, String> map1 = YourClass.mapOf(1, "value1", 2, "value2");
Map<String, String> map2 = YourClass.mapOf("key1", "value1", "key2", "value2");

Note: in Java 9 you can use Map.of


Another approach may be writing special function to extract all elements values from one string by regular-expression:

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main (String[] args){
        HashMap<String,Integer> hashMapStringInteger = createHashMapStringIntegerInOneStat("'one' => '1', 'two' => '2' , 'three'=>'3'  ");

        System.out.println(hashMapStringInteger); // {one=1, two=2, three=3}
    }

    private static HashMap<String, Integer> createHashMapStringIntegerInOneStat(String str) {
        HashMap<String, Integer> returnVar = new HashMap<String, Integer>();

        String currentStr = str;
        Pattern pattern1 = Pattern.compile("^\\s*'([^']*)'\\s*=\\s*>\\s*'([^']*)'\\s*,?\\s*(.*)$");

        // Parse all elements in the given string.
        boolean thereIsMore = true;
        while (thereIsMore){
            Matcher matcher = pattern1.matcher(currentStr);
            if (matcher.find()) {
                returnVar.put(matcher.group(1),Integer.valueOf(matcher.group(2)));
                currentStr = matcher.group(3);
            }
            else{
                thereIsMore = false;
            }
        }

        // Validate that all elements in the given string were parsed properly
        if (currentStr.length() > 0){
            System.out.println("WARNING: Problematic string format. given String: " + str);
        }

        return returnVar;
    }
}

참고URL : https://stackoverflow.com/questions/8261075/adding-multiple-entries-to-a-hashmap-at-once-in-one-statement

반응형