Search in sources :

Example 1 with City

use of com.olive.java.start.java8.entity.City in project olive by ClareTung.

the class StreamCollectorsGroupingByOrder method main.

public static void main(String[] args) {
    City c1 = new City("安徽省", "安庆市");
    City c2 = new City("安徽省", "芜湖市");
    City c3 = new City("上海市", "青浦区");
    City c4 = new City("浙江省", "杭州市");
    City c5 = new City("上海市", "徐汇区");
    List<City> cityList = Lists.newArrayListWithCapacity(5);
    cityList.add(c1);
    cityList.add(c2);
    cityList.add(c3);
    cityList.add(c4);
    cityList.add(c5);
    System.out.println("- - - List - - -");
    cityList.forEach(city -> System.out.println(city.getProvince() + "- - -" + city.getCity()));
    // Map<String, List<City>> cityMap = cityList.stream().collect(Collectors.groupingBy(City::getProvince));
    /*
         * groupingBy(classifier, HashMap::new, downstream);
         * HashMap的底层是哈希表,是无序的,存取数据不同
         */
    Map<String, List<City>> cityMap = cityList.stream().collect(Collectors.groupingBy(City::getProvince, LinkedHashMap::new, Collectors.toList()));
    System.out.println("- - - 分组转换成Map后 - - -");
    cityMap.forEach((key, value) -> value.forEach(city -> System.out.println(city.getProvince() + "- - -" + city.getCity())));
}
Also used : LinkedHashMap(java.util.LinkedHashMap) List(java.util.List) Lists(com.google.common.collect.Lists) Map(java.util.Map) City(com.olive.java.start.java8.entity.City) Collectors(java.util.stream.Collectors) List(java.util.List) City(com.olive.java.start.java8.entity.City)

Aggregations

Lists (com.google.common.collect.Lists)1 City (com.olive.java.start.java8.entity.City)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 Map (java.util.Map)1 Collectors (java.util.stream.Collectors)1