不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2022-04-04 12:14:37  修改时间:2024-03-27 03:30:20  分类:Java基础  编辑

操作示例:

//(1)Map 的 value 为对象的“某个字段值”
Map<String,String> map = userList.stream().collect(Collectors.toMap(User::getId, User::getName, (n1, n2) -> n2));
// 指定返回TeeMap实例,按Key的升序排序
Map<String,String> map = userList.stream().collect(Collectors.toMap(User::getId, User::getName, (n1, n2) -> n2, TreeMap::new));
// 指定返回LinkedHashMap实例,保留原有的顺序 ——>> 【常用】利用SQL查询来排序
Map<String,String> map = userList.stream().collect(Collectors.toMap(User::getId, User::getName, (n1, n2) -> n2, LinkedHashMap::new));

//(2)Map 的 value 为对象“本身”
Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, t -> t));
// 或:
Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

//(3)收集某个字段的值 列表
List<String> roleNameList = authRoleList.stream().map(AuthRole::getRoleName).collect(Collectors.toList()); //【注意】返回的是ArrayList实例

 




 

1、List转Map

lombok注解详解

// 这里的注解作用可点击上方链接
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public static class User{
	private String id;
	private String name;
}

list转map示例

// ::用于类与方法之间,如person -> person.getAge();可以替换成Person::getAge
List<User> userList = Lists.newArrayList(
		new User().setId("A").setName("张三"),
		new User().setId("B").setName("李四"), 
		new User().setId("C").setName("王五")
);
Map<String,String> map =  userList.stream().collect(Collectors.toMap(User::getId, User::getName));
System.out.println(map);

输出:

{A=张三, B=李四, C=王五}

其中Collectors.toMap 有三个重载方法,四个参数:

  1. keyMapper:Key 的映射函数
  2. valueMapper:Value 的映射函数
  3. mergeFunction:当 Key 冲突时,调用的合并方法
  4. mapSupplier:Map 构造器,在需要返回特定的 Map 时使用

当然,如果希望得到 Map 的 value 为对象本身时,可以这样写:

userList.stream().collect(Collectors.toMap(User::getId, t -> t));
// 或:
userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
{A=User(id=A, name=张三), B=User(id=B, name=李四), C=User(id=C, name=王五)}

如果键值重复用前面的会报错,所以加上第三个参数,如果有相同key做出处理

List<User> userList = Lists.newArrayList(
        new User("A","张三"),
        new User().setId("A").setName("李四"),
        new User().setId("A").setName("桃源"),
        new User().setId("C").setName("王五")
);
Map<String,String> map =  userList.stream().collect(Collectors.toMap(User::getId, User::getName, (n1, n2) -> n1+","+n2));
System.out.println(map);
{A=张三,李四,桃源, C=王五}

第四个参数是排序,这里根据treeMap排序(根据key排序)

List<User> userList = Lists.newArrayList(
        new User("2","张三"),
        new User().setId("23").setName("李四"),
        new User().setId("17").setName("桃源"),
        new User().setId("1").setName("王五")
);
Map<String,String> map =  userList.stream().collect(Collectors.toMap(User::getId, User::getName, (n1, n2) -> n1, TreeMap::new));
System.out.println(map);
{1=王五, 17=桃源, 2=张三, 23=李四}

2、List转List

两个不同对象的列表,但是有相同字段。

// 通过stream().map在map方法里面进行转换
// 其中o对list1的对象,return出来的对象代表list2中的对象。
// BeanUtils类的copyProperties方法是把o中与entity相同字段数据从o转到entity
 List<StudentEntity> list1 = new ArrayList<>();
 List<LessonStudentEntity> list2 = list1.stream().map(o -> {
            LessonStudentEntity entity = new LessonStudentEntity();
            BeanUtils.copyProperties(o, entity);
            return entity;
        }).collect(Collectors.toList());
list2.forEach(System.out::println);

工作中的一段代码 示例:

// 缓存“角色名”到用户扩展表(user_ext),多个值以","分隔
String roleNames = "";
List<AuthRole> authRoleList = iAuthRoleService.listByIds(roleIds);
if (ObjectUtil.isNotEmpty(authRoleList)) {
	List<String> roleNameList = authRoleList.stream().map(AuthRole::getRoleName).collect(Collectors.toList());
	roleNames = CollectionUtil.join(roleNameList, ",");
}

 

3、List排序

(1) 使用年龄进行升序排序

List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList());

(2) 使用年龄进行降序排序(使用reversed()方法)

List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed()).collect(Collectors.toList());

(3) 使用年龄进行降序排序,年龄相同再使用身高升序排序(根据2个字段排序)

List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight))
                .collect(Collectors.toList());

4、List循环遍历

对列表中每个对象字段进行操作

// 单行操作
list.stream().forEach(o -> 
	o.setHead("头像") 
);
// 多行操作,用大括号
list.stream().forEach(o -> {
	o.setHead("头像");
	o.setName("名称");
});

5、获取List中非重复字段列表(去重)

distinct()方法是用于获取不同的(如list中有两个id为1的实体类,最终获取的collect1 列表中只有一个id为1的)

List<Long> collect1 = list.stream().map(StudentInfo::getId).distinct().collect(Collectors.toList());

6、根据某个字段去重,并对重复数据操作

例如:当name相同时,去重,并且id进行相加,返回list

List<Ac> list = new ArrayList<Ac>(){
            {
                add(new Ac("A", 1));
                add(new Ac("A", 3));
                add(new Ac("B", 4));
                add(new Ac("B", 5));
            }
        };
 // 第一步:把list转为第一个map,key为name,
 // value为Ac类(a->a表示Ac对象)
 // o1和02表示的是value,这里是Ac对象,
 // 不懂list转map的可以看上面的list转map
Map<String, Ac> map= list.stream()
                .collect(Collectors.toMap(Ac::getName, a -> a, (o1,o2)-> {
                    o1.setId(o1.getId() + o2.getId());
                    return o1;
                }));
 // 第二步:获取map的所有values,生成一个列表到result。
List<Ac> result = result.values().stream().collect(Collectors.toList());

System.out.println("map:"+map);
System.out.println("result:"+result);

输出结果

map:{A=Ac(name=A, id=4), B=Ac(name=B, id=9)}
result:[Ac(name=A, id=4), Ac(name=B, id=9)]

7、获取两个List的交集、差集、并集

 List<String> list1 = new ArrayList<>();
 list1.add("1");
 list1.add("2");
 List<String> list2 = new ArrayList<>();
 list2.add("2");
 list1.add("3");
       
       // 交集
        List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());

        // 差集 (list1 - list2)
        List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());

        // 差集 (list2 - list1)
        List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());

        // 并集
        List<String> listAll = list1.parallelStream().collect(Collectors.toList());
        List<String> listAll2 = list2.parallelStream().collect(Collectors.toList());
        listAll.addAll(listAll2);

        // 去重并集
        List<String> listAllDistinct = listAll.stream().distinct().collect(Collectors.toList());

8、交换List中两个对象位置

交换list中第1个和第2个对象的位置。

Collections.swap(list, 0, 1);

 

 

参考:

  1. https://blog.csdn.net/weixin_44183847/article/details/118892732
  2. https://blog.csdn.net/lu930124/article/details/77595585