Java 8 - Collections.groupingBy result order

I am preparing for the Java exam and have one question that made me a lot of time. Although I study this hard, I cannot determine what determines the order of the result.

Look please:

class Country {

    public enum Continent {
        ASIA, EUROPE
    }
    String name;
    Continent region;

    public Country(String na, Continent reg) {
        name = na;
        region = reg;
    }

    public String getName() {
        return name;
    }

    public Continent getRegion() {
        return region;
    }
}

public class OrderQuestion {

    public static void main(String[] args) {
        List<Country> couList = Arrays.asList(
                new Country("Japan", Country.Continent.ASIA),
                new Country("Italy", Country.Continent.EUROPE),
                new Country("Germany", Country.Continent.EUROPE));
        Map<Country.Continent, List<String>> regionNames = couList.stream()
                .collect(Collectors.groupingBy(Country::getRegion,
                        Collectors.mapping(Country::getName, Collectors.toList())));
        System.out.println(regionNames);
    }
}

What is the result?

A. {EUROPE = [Italy, Germany], ASIA = [Japan]}
B. {ASIA = [Japan], EUROPE = [Italy, Germany]}
C. {EUROPE = [Germany, Italy], ASIA = [Japan]}
D. {EUROPE = [Germany], EUROPE = [Italy], ASIA = [Japan]}

and most importantly, what determines a specific result, and not another?

+4
source share
1 answer

We can eliminate D, because the keys in Map must be unique, which are not executed for EUROPE.

We can exclude Cdue to order in [Germany, Italy]. Italywas placed in front of Germanythe list, so it should also be stored in that order in the list of results.

, B A? , .

-. -, LinkedHashMap, , TreeMap, Collectors.groupingBy.

, HashMap, - hashCode() (Country.Continent enum here) , . hashCode() Enum Object, , , JVM, , - ( , ).

, - Map, groupingBy, , A, B.

+6

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


All Articles