ラムダ式のJava 1.8(Javaの8)でJava 8
が、これはイテレータのようになります集約操作(ストリーム操作)からのforEachメソッドを使用して、ずっと簡単になってきましたIterableインターフェイスから。
はちょうどあなたのコードに文の下にペーストをコピーして、キーと値のペアをプリントアウトしてお使いの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));
はラムダ式を用いた例である。
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を使用することができます。Oracleのドキュメントへのドキュメントリンクを含む
Spliterator sit = hm.entrySet().spliterator();
UPDATE
。 詳細についてラムダこれに行くlinkそしてAggregate Operationsを読む必要があり、Spliteratorのためにこれはlinkに行く。
ラムダを使用しているJava 8:http://stackoverflow.com/a/25616206/1503859 –