Java 8 stream min does not return expected value

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());

    // Getting min
    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.

+4
source share
2 answers

Stream::min -, Comparator. Integer::min , . Integer::compare.

+6

mapToInt() Stream<Integer> IntStream, min() :

int min = l.stream()
        .map(Map::values)
        .flatMap(Collection::stream)
        .mapToInt(Integer::intValue)
        .min().orElse(defaultMinValue);
0

Source: https://habr.com/ru/post/1674694/


All Articles