1.属性-->对象
2.属性-->属性
3.属性--->集合
关联到的api:
1.java8关于集合非空的判断
2.重复key 的问题的处理
3.@postConstrutor相当于static静态代码块
4.java8中的两个Stream()方法和collect()方法是很重要的
说了这么多,最直接的就是上代码,这样问题是最直观和容易解决的
private static List<Apple> list; //初始化 @PostConstruct public void init() { list = Lists.newArrayList( new Apple(1, 10, "red"), new Apple(2, 5, "yellow"), new Apple(3, 2, "green"), new Apple(4, 15, "green"), new Apple(5, 2, "red")); } /** * 属性:对象的形式 * 1.判断集合是否为空 * * @return */ @RequestMapping("/list") public Object getResult() { System.out.println("6=========list转换为map=======key:对象=================="); Map<Integer, Apple> appleMap = (Map<Integer, Apple>) Optional.ofNullable(list) .orElse(Collections.EMPTY_LIST).stream() .collect(Collectors.toMap(Apple::getId, apple1 -> apple1)); System.out.println(JSONObject.toJSONString(appleMap)); return JSON.toJSON(appleMap); } @RequestMapping("/listP") public Object getResult1() { System.out.println("6=========list转换为map=======属性:属性=================="); System.out.println("6=========重复key不异常写法=================="); Map<Integer, Apple> appleMap = (Map<Integer, Apple>) Optional.ofNullable(list) .orElse(Collections.EMPTY_LIST).stream() .collect(Collectors.toMap(Apple::getWeight, Function.identity(), (oldData, newData) -> newData)); System.out.println(JSONObject.toJSONString(appleMap)); return JSON.toJSON(appleMap); } @RequestMapping("listToMapGroup") public Object listToMapGroup() { System.out.println("6=========list转换为map======key:value(颜色属性:对象集合)=================="); Map<Integer, Apple> appleMap = (Map<Integer, Apple>) Optional.ofNullable(list).orElse(Collections.EMPTY_LIST) .stream().collect(Collectors.groupingBy(Apple::getWeight)); return JSON.toJSON(appleMap); } @RequestMapping("listToMapDuptiteKey") public Object listToMapDuptiteKey() { System.out.println("6=========重复key不异常写法=================="); Map<Integer, Apple> appleMap = (Map<Integer, Apple>) Optional.ofNullable(list).orElse(Collections.EMPTY_LIST) .stream().collect(Collectors.toMap(Apple::getWeight, Apple::getColor, (oldData, newData) -> newData)); return JSON.toJSON(appleMap); }