Programming

각 해시 맵에 대한 방법?

procodes 2020. 2. 14. 23:50
반응형

각 해시 맵에 대한 방법? [복제]


이 질문에는 이미 답변이 있습니다.

이 필드가 있습니다 :

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

각각에 대해 의 값 (HashMap 자체 임) 인 항목 Hash<String, HashMap>을 만들어야합니다 .ComboBoxHashMap <String, **HashMap**>

(작동하지 않는) 데모를 통해 :

for (int i=0; i < selects.size(); i++) {
    HashMap h = selects[i].getValue();
    ComboBox cb = new ComboBox();

    for (int y=0; y < h.size(); i++) {
        cb.items.add(h[y].getValue);
    }
}

나는 그 사람에 대해 조금 늦었다는 것을 알고 있지만 다른 사람을 돕기 위해 내가 한 일을 공유 할 것입니다.

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

for(Map.Entry<String, HashMap> entry : selects.entrySet()) {
    String key = entry.getKey();
    HashMap value = entry.getValue();

    // do what you have to do here
    // In your case, another loop.
}

람다 식 자바 8

Java 1.8 (Java 8)에서는 Iterable Interface의 반복자와 유사한 집계 작업 ( Stream operations )의 forEach 메소드를 사용하여 훨씬 쉬워졌습니다 .

아래 명령문을 코드에 복사하고 HashMap 변수의 이름 hm 에서 HashMap 변수로 바꾸어 키-값 쌍을 인쇄하십시오.

HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
 *     Logic to put the Key,Value pair in your HashMap hm
 */

// Print the key value pair in one line.
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));

다음은 Lambda Expression 이 사용되는 예입니다.

    HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
    Random rand = new Random(47);
    int i=0;
    while(i<5){
        i++;
        int key = rand.nextInt(20);
        int value = rand.nextInt(50);
        System.out.println("Inserting key: "+key+" Value: "+value);
        Integer imap =hm.put(key,value);
        if( imap == null){
            System.out.println("Inserted");
        }
        else{
            System.out.println("Replaced with "+imap);
        }               
    }

    hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));

Output:

Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11

또한 Spliterator사용할 수 있습니다 .

Spliterator sit = hm.entrySet().spliterator();

최신 정보


Oracle Docs에 대한 설명서 링크 포함 Lambda 에 대한 자세한 내용을 보려면이 링크 로 이동하여 집계 작업을 읽어야 하며 Spliterator의 경우이 링크 로 이동 하십시오 .


Map.values():

HashMap<String, HashMap<SomeInnerKeyType, String>> selects =
    new HashMap<String, HashMap<SomeInnerKeyType, String>>();

...

for(HashMap<SomeInnerKeyType, String> h : selects.values())
{
   ComboBox cb = new ComboBox();
   for(String s : h.values())
   {
      cb.items.add(s);
   }
}

HashMap반복자를 사용하여 (및 다른 많은 컬렉션)을 반복 할 수 있습니다 .

HashMap<T,U> map = new HashMap<T,U>();

...

Iterator it = map.values().iterator();

while (it.hasNext()) {
    System.out.println(it.next());
}

스트림 자바 8

람다 식forEach 을 허용하는 메서드 와 함께 Java 8 에도 스트림 API 가 있습니다 .

항목 반복 (forEach 및 Stream 사용) :

sample.forEach((k,v) -> System.out.println(k + "=" + v)); 
sample.entrySet().stream().forEachOrdered((entry) -> {
            Object currentKey = entry.getKey();
            Object currentValue = entry.getValue();
            System.out.println(currentKey + "=" + currentValue);
        });
sample.entrySet().parallelStream().forEach((entry) -> {
            Object currentKey = entry.getKey();
            Object currentValue = entry.getValue();
            System.out.println(currentKey + "=" + currentValue);
        });

스트림의 장점은 스트림을 쉽게 병렬화 할 수 있으며 여러 CPU를 폐기 할 때 유용 할 수 있다는 것입니다. 우리는 단순히 parallelStream()대신 사용해야 stream()합니다. 병렬 스트림을 사용 forEach하면 forEachOrdered성능에 차이가없는 것처럼 사용하는 것이 더 합리적 입니다. 우리가 키를 반복하고 싶다면 sample.keySet()and 값을 사용할 수 있습니다 sample.values().

스트림을 사용 forEachOrdered하지 forEach않습니까?

스트림은 또한 forEach방법 을 제공 하지만 스트림의 정의 된 발생 순서가있는 경우 스트림발생 순서 에서이 스트림의 각 요소에 대해 동작을 수행하는 경우 동작 forEach은 명시 적으로 비 결정적 입니다. 따라서 주문이 유지된다는 보장은 없습니다. 이것도확인하십시오 .forEachOrderedforEach


나는 일반적으로 cx42net과 동일하지만 항목을 명시 적으로 생성하지는 않습니다.

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
for (String key : selects.keySet())
{
    HashMap<innerKey, String> boxHolder = selects.get(key);
    ComboBox cb = new ComboBox();
    for (InnerKey innerKey : boxHolder.keySet())
    {
        cb.items.add(boxHolder.get(innerKey));
    }
}

이것은 나에게 가장 직관적 인 것처럼 보입니다.지도의 가치를 반복하는 것에 대해 편견을 가지고 있다고 생각합니다.


사용 entrySet,

/**
 *Output: 
D: 99.22
A: 3434.34
C: 1378.0
B: 123.22
E: -19.08

B's new balance: 1123.22
 */

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MainClass {
  public static void main(String args[]) {

    HashMap<String, Double> hm = new HashMap<String, Double>();

    hm.put("A", new Double(3434.34));
    hm.put("B", new Double(123.22));
    hm.put("C", new Double(1378.00));
    hm.put("D", new Double(99.22));
    hm.put("E", new Double(-19.08));

    Set<Map.Entry<String, Double>> set = hm.entrySet();

    for (Map.Entry<String, Double> me : set) {
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    }

    System.out.println();

    double balance = hm.get("B");
    hm.put("B", balance + 1000);

    System.out.println("B's new balance: " + hm.get("B"));
  }
}

여기에 완전한 예가 있습니다.

참고 URL : https://stackoverflow.com/questions/4234985/how-to-for-each-the-hashmap



반응형