话不多说直接上代码
package com.leinuo.jvm.list; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; public class App { public static void main(String[] args) { listDistinct(); } public static void listDistinct(){ System.out.println("根据VIP order去重保留最先重复的数据-------1----2---" ); List<VIP> collect1 = Arrays.stream(VIP.values()).collect(Collectors.toList()); collect1 = collect1 .stream() .collect( Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(VIP::getOrder))), ArrayList::new ) ); System.out.println("根据VIP order去重并排序-------1-------"+collect1.toString() ); List<VIP> collect2 = Arrays.stream(VIP.values()).collect(Collectors.toList()); collect2 = collect2.stream().filter(distinctByKey(VIP::getOrder)).collect(Collectors.toList()); System.out.println("根据VIP order去重并排序-------2-------"+collect2.toString() ); System.out.println("根据VIP order去重保留最后重复的数据-------3----4---5--" ); List<VIP> collect3 = Arrays.stream(VIP.values()).collect(Collectors.toList()); Collections.reverse(collect3); collect3 = collect3 .stream() .collect( Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(VIP::getOrder))), ArrayList::new ) ); System.out.println("根据VIP order去重并排序-------3-------"+collect3.toString() ); List<VIP> collect4 = Arrays.stream(VIP.values()).collect(Collectors.toList()); Collections.reverse(collect4); collect4 = collect4 .stream() .filter(distinctByKey(VIP::getOrder)) .sorted(Comparator.comparing(VIP::getOrder)) .collect(Collectors.toList()); System.out.println("根据VIP order去重并排序-------4-------"+collect4.toString() ); List<VIP> collect5 = Arrays.stream(VIP.values()).collect(Collectors.toList()); collect5 = collect5.stream().collect(Collectors .toMap(VIP -> { return VIP.getOrder();},Function.identity(), (e1, e2) -> e2)) .values().stream().collect(Collectors.toList()); Collections.reverse(collect5); System.out.println("根据VIP order去重并排序-------5-------"+collect5.toString() ); } private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } }
public enum VIP { VIP1(6), VIP2(5), VIP3(4), VIP4(2), VIP5(2), VIP6(1); private Integer order; VIP(int order) { this.order = order; } public Integer getOrder() { return order; } public void setOrder(Integer order) { this.order = order; } }
标签:stream,Collectors,更具,list,order,-------,collect,VIP,java8 From: https://www.cnblogs.com/leinuo2016/p/16715663.html