Wednesday, 18 October 2017

dictionary - How do I efficiently iterate over each entry in a Java Map?

The ordering will always depend on the specific map
implementation.
Using Java 8 you can use either of
these:



map.forEach((k,v) -> {
System.out.println(k + ":" + v);
});



Or:



map.entrySet().forEach((e)
-> {
System.out.println(e.getKey() + " : " + e.getValue());

});


The result will be
the same (same order). The entrySet backed by the map so you are getting the same order.
The second one is handy as it allows you to use lambdas, e.g. if you want only to print
only Integer objects that are greater than
5:




map.entrySet()

.stream()
.filter(e-> e.getValue() > 5)

.forEach(System.out::println);


The
code below shows iteration through LinkedHashMap and normal HashMap (example). You will
see difference in the
order:



public class HMIteration
{



public static void main(String[] args)
{
Map linkedHashMap = new
LinkedHashMap<>();
Map hashMap = new
HashMap<>();

for (int i=10; i>=0; i--) {

linkedHashMap.put(i, i);
hashMap.put(i, i);

}


System.out.println("LinkedHashMap (1): ");

linkedHashMap.forEach((k,v) -> { System.out.print(k + " (#="+k.hashCode() + "):" + v
+ ", "); });

System.out.println("\nLinkedHashMap (2):
");

linkedHashMap.entrySet().forEach((e) -> {

System.out.print(e.getKey() + " : " + e.getValue() + ", ");

});



System.out.println("\n\nHashMap (1):
");
hashMap.forEach((k,v) -> { System.out.print(k + " (#:"+k.hashCode() +
"):" + v + ", "); });

System.out.println("\nHashMap (2):
");

hashMap.entrySet().forEach((e) -> {

System.out.print(e.getKey() + " : " + e.getValue() + ", ");
});

}

}


readability="57">

LinkedHashMap (1):




10 (#=10):10, 9 (#=9):9, 8 (#=8):8, 7 (#=7):7, 6 (#=6):6, 5
(#=5):5, 4 (#=4):4, 3 (#=3):3, 2 (#=2):2, 1 (#=1):1, 0 (#=0):0,




LinkedHashMap (2):





10 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 1 : 1, 0 :
0,



HashMap (1):




0 (#:0):0, 1 (#:1):1, 2 (#:2):2, 3 (#:3):3, 4 (#:4):4, 5 (#:5):5, 6
(#:6):6, 7 (#:7):7, 8 (#:8):8, 9 (#:9):9, 10 (#:10):10,




HashMap (2):



0 : 0, 1 : 1, 2 : 2, 3 :
3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 :
10,


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...