java8-list TO map

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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值