一路向北hhh level
获赞
16
粉丝
1
关注
0
看过 TA
4
门头沟学院
2021
Java
IP属地:上海
暂未填写个人简介
私信
关注
2022-05-17 00:17
门头沟学院 Java
FARO_Z:答案无法设置代码格式,复制到 ide 里凑合看吧: ```java public class TableSerializer { @Test void tableSerializerTest() { List<Address> addresses = new ArrayList<>(); addresses.addAll(Arrays.asList(new Address("1", "北京市", 1, "0",new ArrayList<>()), new Address("2", "朝阳区", 2, "1",new ArrayList<>()), new Address("3", "望京街道", 3, "2",new ArrayList<>()), new Address("4", "海淀区", 2, "1",new ArrayList<>()))); TableSerializer serializer = new TableSerializer(); List<Address> serializedAddresses = serializer.serialize(addresses); Gson gson = new Gson(); System.out.println(gson.toJson(serializedAddresses)); } public List<Address> serialize(List<Address> addresses) { HashMap<String, List<Address>> idMap = new HashMap<>(); ArrayList<Address> res = new ArrayList<>(); for (Address address : addresses) { idMap.putIfAbsent(address.getPid(), new ArrayList<>()); idMap.get(address.getPid()).add(address); } res.addAll(idMap.get("0")); for (Address address : addresses) { address.children.addAll(Optional .ofNullable(idMap.get(address.getId())) .orElseGet(()->new ArrayList<>())); } return res; } @Data @AllArgsConstructor @NoArgsConstructor static class Address { private String id; private String name; private Integer level; private String pid; private List<Address> children; } } ```查看图片
0 点赞 评论 收藏
分享
关注他的用户也关注了:
牛客网
牛客企业服务