I am looking to get minimum value from a list of maps in java. I am using combination of flatmap,stream and min to do so and not getting expected results. Here is the code public class TestMin {
public static class TestHolder{
public static Map<String,Integer> getValues(){
Map<String,Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",3);
map.put("c",2);
return map;
}
}
public static void main(String[] args) {
List<Map<String, Integer>> l = new ArrayList<>();
l.add(TestHolder.getValues());
l.add(TestHolder.getValues());
l.add(TestHolder.getValues());
// Getting min
int min = l.stream().map((m)->m.values()).flatMap((v)->v.stream()).min(Integer::min).get();
System.out.println(min);
}
}
Output is: 2
Of course, the output that I am expecting is 1. Trying some debugging suggests that it is providing an output a value corresponding to "c". i.e if map looks like
[a->2 , b->3, c->1]
Then the output I am getting is 1. The question is why it is not sorting by values and rather sorting by keys and providing me the unexpected output.