java list转化为map如何提取某个字段为key?

list =[ {"id": 2, "name": "san"}, {"id": 3, "name": "si"}]

我想转为:

map = "2": {"id": 2, "name": "san"}, "3":{"id": 3, "name": "si"}


回答:

import java.util.*;

import java.util.stream.*;

public class Main {

public static void main(String[] args) {

List<Map<String, Object>> list = new ArrayList<>();

Map<String, Object> item1 = new HashMap<>();

item1.put("id", 2);

item1.put("name", "san");

list.add(item1);

Map<String, Object> item2 = new HashMap<>();

item2.put("id", 3);

item2.put("name", "si");

list.add(item2);

Map<Integer, Map<String, Object>> map = list.stream()

.collect(Collectors.toMap(

item -> (Integer) item.get("id"),

item -> item

));

System.out.println(map);

}

}


回答:

和楼上不同的一个非stream的版本:

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

public class Main {

public static void main(String[] args) {

List<Map<String, Object>> list = getList();

Map<String, Map<String, Object>> map = new HashMap<>();

for (Map<String, Object> element : list) {

String id = element.get("id").toString();

map.put(id, element);

}

System.out.println(map);

}

private static List<Map<String, Object>> getList() {

// 假设这是你的列表

List<Map<String, Object>> list = new ArrayList<>();

Map<String, Object> element1 = new HashMap<>();

element1.put("id", 2);

element1.put("name", "san");

list.add(element1);

Map<String, Object> element2 = new HashMap<>();

element2.put("id", 3);

element2.put("name", "si");

list.add(element2);

return list;

}

}

以上是 java list转化为map如何提取某个字段为key? 的全部内容, 来源链接: utcz.com/p/945275.html

回到顶部