使用jdk1.8 新特性 使用stream 按属性去重
工具/原料
方法/步骤
1创建dto:@Setter @Getter public class StreamDto { private String uuid ; private String name; public StreamDto(String uuid, String name){ this.uuid = uuid; this.name = name; } }
2创建工具类:public class StreamUtils { /** * 对象去重 * @param stringList */ public static List removeDuplicate(List stringList){ List uniqueByNameAndSex = stringList.stream().collect( Collectors. collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getUuid() + ';' + o.getName()))), ArrayList::new)); return uniqueByNameAndSex; } }
3测试案例:public class TestStream { @Test public void removeDuplicate(){ List stringList = new ArrayList<>(); stringList.add(new StreamDto('abc','张三')); stringList.add(new StreamDto('cdf','李四')); stringList.add(new StreamDto('abc','张三')); List streamDtoList = StreamUtils.removeDuplicate(stringList); streamDtoList.stream().forEach(streamDto -> System.out.println(streamDto.getUuid() + ';' + streamDto.getName())); } }
4运行结果:abc;张三cdf;李四 Process finished with exit code 0