stream 对象去重
1、创建dto:@Setter@Getterpublic 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<StreamDto> removeDuplicate(List<StreamDto> stringList){ List<StreamDto> 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 publi罕铞泱殳c void r髫潋啜缅emoveDuplicate(){ List<StreamDto> stringList = new ArrayList<>(); stringList.add(new StreamDto("abc","张三")); stringList.add(new StreamDto("cdf","李四")); stringList.add(new StreamDto("abc","张三")); List<StreamDto> streamDtoList = StreamUtils.removeDuplicate(stringList); streamDtoList.stream().forEach(streamDto -> System.out.println(streamDto.getUuid() + ";" + streamDto.getName())); }}
4、运行结果:abc;张三cdf;李四Process finished with exit code 0