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);
}
本文通过实例演示了Java8中Stream API的使用方法,包括如何将List转换为Map,处理重复键的问题,以及如何利用Optional和Collectors进行非空判断和集合操作。深入探讨了属性到对象、属性到属性及属性到集合的转换过程。
1356

被折叠的 条评论
为什么被折叠?



