How to print keys & values of a Map using Java 8
Categories: Java 8(JDK1.8) Java Java Examples
package r4r.co.in;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public class MapExamplesJava8 {
public static void main(String[] args) {
// How to print keys & values of a Map using Java 8
Map<String,String> map= new HashMap<String, String>();
map.put("Key-1","value-1");
map.put("Key-2","value-2");
map.put("Key-3","value-3");
map.put("Key-4","value-4");
//using forEachRemaining
//Using Java 8 – Collection.iterator() and Iterator.forEachRemaining()
map.entrySet().iterator().forEachRemaining(System.out::println);
//all values
map.values().forEach(System.out::println);
//Using Java 8 – Collection.stream() and Stream.forEach()
map.entrySet().stream().forEach(System.out::println);
//Stream -keys and values.
Stream.of(map).map(m->m.keySet()).forEach(System.out::println);
Stream.of(map).map(m->m.values()).forEach(System.out::println);
//Using Java 8 – Stream.of() + Collection.toArray() + Stream.forEach()
Stream.of(map.entrySet().toArray()).forEach(System.out::println);
//Using Java 8 - Stream.of() and Collection.toString() and Stream.forEach()
Stream.of(map.entrySet().toString()).forEach(System.out::println);
}
}
Output
Key-1=value-1
Key-2=value-2
Key-3=value-3
Key-4=value-4
value-1
value-2
value-3
value-4
[Key-1, Key-2, Key-3, Key-4]
[value-1, value-2, value-3, value-4]
Key-1=value-1
Key-2=value-2
Key-3=value-3
Key-4=value-4
[Key-1=value-1, Key-2=value-2, Key-3=value-3, Key-4=value-4]