I'm learning about Java 8 streams API by trying different examples. I'm trying to form a HashMap from an ArrayList using streams .map() method. (I know about .groupingBy method but i am trying to understand the underlying logic of stream operations.) When i run my code without calling the forEach() method (or any terminal operation) changes are not being applied to my HashMap<> and it stays empty. But calling a terminal operation enable to protect changes i made. I was thinking that terminal operations used only to return non-stream values and end streams. Can anyone explain why this is happening like this ?
class Main {
public static void main(String[] args) {
// Create a list of arrays then form a HasMap based on entries of list
List<String[]> list3 = new ArrayList<String[]>();
String[] entry1 = {"a","b","c"};
String[] entry2 = {"d","e","f"};
String[] entry3 = {"g","h","i"};
list3.add(entry1);
list3.add(entry2);
list3.add(entry3);
// hashmap
HashMap<String, String[]> map1 = new HashMap<String, String[]>();
// streamize the list to form hashmap
list3.stream()
.map(entry -> {
String key = entry[0];
String[] value = {entry[1],entry[2]};
map1.put(key, value);
// must return a String[]
return entry;
})
// CHANGES ARE ONLY APPLIED WHEN TERMINAL OPERATIONS CALLED ???
.forEach(entry -> {});
// print elements
for (Map.Entry<String,String[]> entry : map1.entrySet()) {
System.out.println(entry);
}
}
// Without terminal op
//Empty
// With terminal op
a=[Ljava.lang.String;@7921b0a2
d=[Ljava.lang.String;@174d20a
g=[Ljava.lang.String;@66d2e7d9