I want to get the minimum value from a list of maps in java. I use a combination of flatmap, stream and min for this and do not get the expected results. Here is the code for the open 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());
int min = l.stream().map((m)->m.values()).flatMap((v)->v.stream()).min(Integer::min).get();
System.out.println(min);
}
}
Output: 2
Of course, the conclusion I am expecting is 1. Attempting some debugging assumes that it provides the output with a value corresponding to "c". If the card looks like
[a->2 , b->3, c->1]
Then the output that I get is 1. The question is why it doesn't sort by values ββand rather sort by keys and provides me with an unexpected result.
source
share