java8 list新特性
1 import com.google.common.collect.Lists; 2 3 import java.math.BigDecimal; 4 import java.util.*; 5 import java.util.function.Function; 6 import java.util.function.Predicate; 7 import java.util.stream.Collectors; 8 import java.util.concurrent.ConcurrentHashMap; 9 10 import static java.util.stream.Collectors.collectingAndThen; 11 import static java.util.stream.Collectors.toCollection; 12 import static java.util.Comparator.comparingLong;; 13 14 public class test { 15 16 public void test(){ 17 List<UserDomain> list = Lists.newArrayList(); 18 //判断对象属性去重 19 long count = list.stream().filter(distinctByKey(UserDomain :: getUserName)).distinct().count(); 20 if(count < list.size()){ 21 22 } 23 24 //根据对象属性去重 25 list = list.stream().collect( 26 collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(UserDomain::getId))), ArrayList::new) 27 ); 28 //去重 29 list = list.stream().distinct().collect(Collectors.toList()); 30 31 //排序 32 list.sort(Comparator.comparing(UserDomain::getUserName)); 33 list.sort(Comparator.comparing(UserDomain::getUserName).reversed()); 34 list = list.stream().sorted(Comparator.comparing(UserDomain::getUserName, Comparator.nullsFirst(Comparator.naturalOrder()))).collect(Collectors.toList()); 35 list = list.stream().sorted(Comparator.comparing(UserDomain::getUserName, Comparator.nullsFirst(Comparator.naturalOrder())).reversed()).collect(Collectors.toList()); 36 37 //过滤 38 list = list.stream().filter(a -> a.getUserName().equals("张三")).collect(Collectors.toList()); 39 40 //求和 41 BigDecimal totalMoney = list.stream().map(UserDomain::getUnitPrice).reduce(BigDecimal.ZERO, BigDecimal::add); 42 43 //遍历(使用return可以达到continue的效果) 44 list.forEach(userList -> { 45 return; 46 }); 47 //groupBy分组 48 Map<Long, List<UserDomain>> groupBy = list.stream().collect(Collectors.groupingBy(UserDomain::getId)); 49 50 //id为key,对象为value转Map 51 Map<Long,UserDomain> userMap = list.stream().collect(Collectors.toMap(UserDomain::getId, a -> a,(k1,k2)->k1)); 52 //去重 53 userMap = list.stream().collect(Collectors.toMap(UserDomain::getId, user -> user,(k1,k2)->k1)); 54 //JSONArray.toJSONString(userMap); 55 56 //获取对象list中某个属性的值的lis 57 List<String> nameList = list.stream().map(UserDomain::getUserName).collect(Collectors.toList()); 58 List<String> nameList1 = list.stream().map(e -> e.getUserName()).collect(Collectors.toList()); 59 60 61 } 62 63 64 private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { 65 Map<Object, Boolean> seen = new ConcurrentHashMap<>(); 66 return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; 67 } 68 69 }