The complex use of list.stream in Java8

scene 1:

         1.1: Demand   

                 The front end needs to return a json array, which is grouped by region, and there are various scenic spots in each region

                 Areas and scenic spots may be repeated, so they should be removed; each scenic spot is used and separated.

         1.2: Source data

                  The source data is an object, as follows:

                  

        1.3: Resolve

   //根据景区获取位置信息
    public JSONArray groupScenicByArea(List<Item.Scenic> list) {
        HashMap<String, List<String>> resultMap = list.stream().collect(
                Collectors.groupingBy(
                        scenic -> scenic.getScenicCity(),
                        HashMap::new,
                        Collectors.mapping(
                                (scenic -> scenic.getScenicName().trim()),
                                toList()
                        )
                )
        );

        JSONArray scenicArray = new JSONArray();
        resultMap.forEach((key, value) -> {
            String val = value.stream().distinct().collect(Collectors.joining("、"));
            JSONObject scenicObject = new JSONObject();
            scenicObject.put(key,val);
            scenicArray.add(scenicObject);
        });
        return scenicArray;
    }

       1.4: Results display

 

                

Guess you like

Origin blog.csdn.net/qq_20594019/article/details/112679574