发布于 

Java-list,map常用操作

简单升序和降序
1
2
3
4
List<Long> refactorReports = List.of(5L, 3L, 9L, 1L, 4L);

// 升序排序
Collections.sort(refactorReports, Comparator.naturalOrder());
1
2
3
4
List<Long> refactorReports = List.of(5L, 3L, 9L, 1L, 4L);

// 降序排序
Collections.sort(refactorReports, Comparator.reverseOrder());
List分页
1
2
voList=voList.stream().skip((long) queryDTO.getPageSize() * (queryDTO.getPageNum() - 1))
.limit(queryDTO.getPageSize()).collect(Collectors.toList());
返回其他类型的集合
1
2
3
4
5
6
7
8
9
public static List<ReportTemplateVO> toReportTemplateVO(List<RefactorReportTemplate> templates, RefactorReportContentTemplateService contentTemplateService, Boolean isCopy) {
Map<Long, List<RefactorReportContentTemplate>> contentTemplateMap = contentTemplateService.list().stream().collect(Collectors.groupingBy(RefactorReportContentTemplate::getTemplateBaseId));
return templates.stream()
.map(template -> {
// 根据模板ID获取对应的内容模板列表,如果不存在则返回空列表
List<RefactorReportContentTemplate> ct = contentTemplateMap.getOrDefault(template.getTemplateBaseId(), Collections.emptyList());
return toReportTemplateVO(template, ct, isCopy);
}).collect(Collectors.toList());
}
List用属性名称变量排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if (queryDTO.getAsc()) {
voList.sort(Comparator.comparing(projectRefactorBugVo -> {
try {
Field field = projectRefactorBugVo.getClass().getSuperclass().getDeclaredField(queryDTO.getSortField());
field.setAccessible(true);
return (Comparable) field.get(projectRefactorBugVo);
}catch (Exception e) {
throw new RuntimeException(e);
}}, Comparator.naturalOrder()));
}else {
voList.sort(Comparator.comparing(projectRefactorBugVo -> {
try {
Field field = projectRefactorBugVo.getClass().getSuperclass().getDeclaredField(queryDTO.getSortField());
field.setAccessible(true);
return (Comparable) field.get(projectRefactorBugVo);
}catch (Exception e) {
throw new RuntimeException(e);
}}, Comparator.reverseOrder()));
}
流,双层map
1
2
3
4
Map<String, Map<String, SysDictDataPlus>> dict = sysDictDataPlusService.list(queryWrapperSysDictDataPlus).stream().collect(Collectors.groupingBy(
SysDictDataPlus::getDictType, // 外层Map的键
Collectors.toMap(SysDictDataPlus::getDictValue, e -> e) // 内层Map的键和值
));
流map
1
2
3
4
Map<Long, List<RefactorReportInstance>> ins = instanceService.selectInstanceByInsIds(temIdList)
.stream().collect(Collectors.groupingBy(RefactorReportInstance::getTemplateBaseId));

Map<Long, SysUser> usMap = userService.list().stream().collect(Collectors.toMap(SysUser::getUserId, t -> t));
流单map,单值过滤
1
2
3
4
5
6
7
8
9
10
11
 Map<Long, RefactorReportInstance> collect = instanceService.selectInstanceByInsIds(temIdList).stream().collect(Collectors.toMap(
RefactorReportInstance::getTemplateBaseId, // 作为key
e -> e, // 作为value
(exiValue, newValue) -> { // 当value冲突时
// 比较两个对象的sort字段,返回具有最大sort值的对象
return exiValue.getTemplateInstanceId() >= newValue.getTemplateInstanceId() ? exiValue : newValue;
}
));

Map<Long, RefactorReportInstance> temIns = instanceService.selectInstanceByInsIds(temIdList).stream().collect(Collectors.toMap(
RefactorReportInstance::getTemplateBaseId,e -> e,(exiValue, newValue) -> exiValue.getTemplateInstanceId() >= newValue.getTemplateInstanceId() ? exiValue : newValue));
流,list分组
1
Map<Long, List<SysDept>> deptMapBytParentId = list.stream().collect(Collectors.groupingBy(SysDept::getParentId));
流,是否包含
1
boolean b = refactorReports.stream().anyMatch(person -> person.getTemplateInstanceId().equals(ins.getTemplateInstanceId()));
流,遍历修改list
1
2
3
4
5
6
7
8
9
10
11
List<RefactorReportContentTemplate> up = delRefactorReportContentTemplate.stream().peek(e -> {
e.setDelFlag(CommonConstant.DELETED_BYTE);
e.setUpdateTime(DateTimeUtil.getCurrentBeijingTime());
e.setUpdateBy(user.getUserName());
}).collect(Collectors.toList());

delRefactorReportContentTemplate = delRefactorReportContentTemplate.stream().peek(e -> {
e.setDelFlag(CommonConstant.DELETED_BYTE);
e.setUpdateTime(DateTimeUtil.getCurrentBeijingTime());
e.setUpdateBy(user.getUserName());
}).collect(Collectors.toList());
简单差集
1
2
3
List<Long> diff = reportCountUserIdList.stream()
.filter(e -> !subUserIdList.contains(e))
.collect(Collectors.toList());
简单交集
1
2
3
4
5
6
7
List<Long> list1 = List.of(1L, 2L, 3L);
List<Long> list2 = List.of(2L, 3L, 4L);

List<Long> intersection = list1.stream()
.filter(list2::contains)
.distinct()
.collect(Collectors.toList());
简单并集
1
2
A.addAll(B);
List<String> AuB = A.stream().distinct().collect(Collectors.toList());
对象交集差集

现在有两个类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class ClassA {
String id;
String realName;

public ClassA(String id, String realName) {
this.id = id;
this.realName = realName;
}

@Override
public String toString() {
return "ClassA{" +
"id='" + id + '\'' +
", realName='" + realName + '\'' +
'}';
}

public String getId() {
return id;
}

public String getRealName() {
return realName;
}
}

class ClassB {
String id;
String nickName;

public ClassB(String id, String nickName) {
this.id = id;
this.nickName = nickName;
}

@Override
public String toString() {
return "ClassB{" +
"id='" + id + '\'' +
", nickName='" + nickName + '\'' +
'}';
}

public String getId() {
return id;
}

public String getNickName() {
return nickName;
}
}

现在有两个集合,分别是ClassA对象的集合、ClassB对象的集合

1
2
3
4
5
6
7
8
9
10
11
List<ClassA> aList = new ArrayList<>(Arrays.asList(
new ClassA("1", "张三"),
new ClassA("2", "李四"),
new ClassA("3", "王五")
));
List<ClassB> bList = new ArrayList<>(Arrays.asList(
new ClassB("2", "李某"),
new ClassB("3", "王某"),
new ClassB("4", "赵某")
));

基本思想就是想遍历第一个集合,取出第一个集合中的每个元素的某个属性,并使用这个属性遍历第二个集合,看这个属性是否在第二个集合中存在。相当于是有两层循环。
Java 8中引入了Stream和Lambda表达式,使用它们无需自己编写for循环,只需一行代码就能实现上述功能。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//aList与bList的交集
List<ClassA> intersectA = aList
.stream() //获取第一个集合的Stream1
.filter( //取出Stream1中符合条件的元素组成新的Stream2,lambda表达式1返回值为true时为符合条件
a -> //lambda表达式1,a为lambda表达式1的参数,是Stream1中的每个元素
bList.stream() //获取第二个集合的Stream3
.map(ClassB::getId) //将第二个集合每个元素的id属性取出来,映射成新的一个Stream4
.anyMatch( //返回值(boolean):Stream4中是否至少有一个元素使lambda表达式2返回值为true
id -> //lambda表达式2,id为lambda表达式2的参数,是Stream4中的每个元素
Objects.equals(a.getId(), id) //判断id的值是否相等
)
)
.collect(Collectors.toList()); //将Stream2转换为List
System.out.println(intersectA);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//实际交集示例
List<RefactorReportContentTemplate> upDateRefactorReportContentTemplate = oldContentTemplates.stream()
.filter(a -> newContentTemplates.stream().map(RefactorReportContentTemplate::getId)
.anyMatch(id -> Objects.equals(a.getId(), id))).collect(Collectors.toList());

//多条件扩展
List<RefactorReportContentTemplate> upDateRefactorReportContentTemplate =
oldContentTemplates.stream()
.filter(oldTemplate -> newContentTemplates.stream()
.filter(e -> ObjectUtil.isNotEmpty(e.getId()))
.anyMatch(newTemplate ->
Objects.equals(oldTemplate.getId(), newTemplate.getId()) && (
!oldTemplate.getName().equals(newTemplate.getName()) ||
!oldTemplate.getStatus().equals(newTemplate.getStatus()) ||
!oldTemplate.getContentType().equals(newTemplate.getContentType()) ||
!oldTemplate.getPlaceholder().equals(newTemplate.getPlaceholder()) ||
!oldTemplate.getCannotEdit().equals(newTemplate.getCannotEdit())
))).collect(Collectors.toList());
1
2
3
//bList与aList的差集
List<ClassB> differenceB = bList.stream().filter(b -> aList.stream().map(ClassA::getId).noneMatch(id -> Objects.equals(b.getId(), id))).collect(Collectors.toList());
System.out.println(differenceB);
简单去重
1
2
3
4
 List<Long> makeDepts = new ArrayList<>();
// 假设makeDepts被填充了一些可能包含重复的元素
// 使用Stream API去重
makeDepts = makeDepts.stream().distinct().collect(Collectors.toList());
流类型转换,map
1
2
3
list(queryWrapperBing).stream().collect(Collectors.groupingBy(
sysDataBindPlus -> Long.valueOf(sysDataBindPlus.getMainId()),
Collectors.toList()));
1
Map<Long, List<RefactorReport>> collect = reportList.stream().collect(Collectors.groupingBy(RefactorReport::getTemplateInstanceId, Collectors.toList()));
1
2
Map<Long, User> userMap = userList.stream()
.collect(Collectors.toMap(User::getId, t -> t));
转数组
1
2
long[] pos = sysUserPosts1.stream().mapToLong(SysUserPost::getPostId).toArray();
Long[] pos = sysUserPosts1.stream().map(SysUserPost::getPostId).toArray(Long[]::new);
数组转list
1
List<Long> longList = Arrays.asList(longArray);
List,倒序
1
Collections.sort(voList, (s1, s2) -> s2.getState().compareTo(s1.getState()));
List,升序
1
Collections.sort(voList, Comparator.comparing(ProjectRefactorBugVo::getState));
1
2
3
4
5
if (Strings.isNotBlank(queryDTO.getSortField())) {
if (ObjectUtil.isEmpty(queryDTO.getAsc()))
queryDTO.setAsc(false);
queryWrapper.last("order by " + StrUtil.toUnderlineCase(queryDTO.getSortField()) + " " + ((queryDTO.getAsc()) ? "asc" : "desc"));
}
List 转字符串
1
String join = String.join(", ", list);
去除另外1个list中有的元素
1
2
3
4
newRole = newRole.stream()
.filter(newRoleItem -> oldRole.stream()
.noneMatch(oldRoleItem -> oldRoleItem.getRoleId().equals(newRoleItem.getRoleId())))
.collect(Collectors.toList());

本地懒得启动,就用远程调试。如果要一定要本地调试,就用 ktctl 引导 集群镜像一份流量 到 本地JVM