Java集合操作

301 阅读1分钟

一、List操作

1. List按照字段分组转Map

Map<String, List<Map<String, Object>>> groupData = list.stream().collect(Collectors.groupingBy((data -> {
    String field1 = (String) data.get("field1");
    String field2 = (String) data.get("field2");
    return field1 + "_" + field2;
})));

2. List对象转map

 Map<String, FjyClockInPlan> clockInPlanMap = clockInPlans.stream().collect(Collectors.toMap(FjyClockInPlan::getPlanId, Function.identity(), (key1, key2) -> key2));

3. List按照属性分组

Map<String, List<AppArchivesManageDto>> archivesManageMap = archivesManageList.stream().collect(Collectors.groupingBy(AppArchivesManageDto::getArchivesLocation));

4. 移除数据

返回结果为true时移除

List<Object> list = new ArrayList<>();
list.removeIf(next -> !next.isOK());

5. list转数组

list.stream().map(SysDictData::getDictValue).toArray(String[]::new)

6. list转字符串

String names = selectedUser.stream().map(DbUser::getName).collect(Collectors.joining("、"));

二、 Map转List

1. Map的key转换为List

  Map<String, Integer> map = new HashMap<>();
  map.put("key1", 2);
  map.put("key2", 3);
  map.put("key3", 4);

  List<String> keyList = new ArrayList<>(map.keySet());

2. Map的value转换为List

Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);

List<Integer> keyList = new ArrayList<>(map.values());