java里面List<Object>转map,List<String>

比较常见的工具类,使用guava和java里面的stream实现

package cn.mark.tool;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 

* list转map, *

* * @author : mark * @since : 2022/11/3 19:35 */ public class UTest { public static void main(String[] args) { List list = new ArrayList<>(); Demo demo = new Demo(); demo.setId("2222"); demo.setName("tom"); list.add(demo); List orderList = list.stream().map(Demo::getId).collect(Collectors.toList()); System.out.println(orderList); ImmutableMap orderMap = Maps.uniqueIndex(list.iterator(), Demo::getId); System.out.println(JSONUtil.toJsonStr(orderMap)); } public static class Demo { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }

执行结果如下

[2222]
{"2222":{"id":"2222","name":"tom"}}

你可能感兴趣的:(java,java,json,开发语言)