一、如果List中是字符串时
先将List转为Set集合,再将Set集合转成List
代码如下:
@RunWith(SpringRunner.class) @SpringBootTest(classes = MySpringBootApplication.class) public class ListTest { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("你好"); list.add("早上好"); list.add("你好"); list.add("晚上好"); for (String s : list) { System.out.println(s); }
System.out.println("-----------"); //使用set去重 Set<String> set = new HashSet<>(list); List<String> list1 = new ArrayList<>(set); for (String s : list1) { System.out.println(s); } } }
结果如下:
你好 早上好 你好 晚上好 ----------- 你好 早上好 晚上好
二、如果List中是对象时
Role对象
@Data @AllArgsConstructor public class Role { /** * 角色id主键 */ private Integer roleId; /** * 角色名称 */ private String roleName; /** * 职能描述 */ private String remark; }
测试类:
public class Demo01 { public static void main(String[] args) { Role role1 = new Role(1, "开发", "aa"); Role role2 = new Role(2, "测试", "bb"); Role role3 = new Role(3, "运维", "cc"); Role role4 = new Role(4, "开发", "aa"); List<Role> roles = new ArrayList<>(); roles.add(role1); roles.add(role2); roles.add(role3); roles.add(role4); List<Role> roles1 = new ArrayList<>(); Set<String> set = new HashSet<>(); roles.stream().forEach(item ->{ if (set.add(item.getRoleName())) { roles1.add(item); } }); roles1.stream().forEach(System.out::println); } }
结果:
Role(roleId=1, roleName=开发, remark=aa) Role(roleId=2, roleName=测试, remark=bb) Role(roleId=3, roleName=运维, remark=cc)