jdk1.8新特性集合部分
jdk1.8的stream用来处理集合,可以实现对集合的过滤,查找操作
集合排序sorted()
List<Integer> aList = new ArrayList<>(); aList.add(12); aList.add(14); aList.add(72); aList.add(42); aList.add(92); aList.add(22); aList.add(2); aList.add(10); aList.stream().sorted().forEach(a -> { System.out.println(a); });
集合元素过滤 filter
Stream<Integer> filter = aList.stream().filter(b -> b > 30); filter.sorted().forEach(c -> { System.out.println(c); });
集合数据去重distinct(),通过流中元素的 hashCode()
和 equals()
去除重复元素
Stream<Integer> filter = aList.stream().distinct(); filter.sorted().forEach(c -> { System.out.println("---去重后有序打印:" + c); });
获取n个元素limit(n)
Stream<Integer> filter = aList.stream().sorted().limit(3); filter.forEach(c -> { System.out.println("---获取三个元素打印:" + c); });
将Stream类型转化为我们需要的集合类型
aList = filter.collect(Collectors.toList());
map接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
UmAndCustomerIdParam um=new UmAndCustomerIdParam(); List<UmAndCustomerIdParam> paramList=new ArrayList<UmAndCustomerIdParam>(); paramList.add(new UmAndCustomerIdParam("qiuxie002","a001")); paramList.add(new UmAndCustomerIdParam("qiuxie002","a002")); paramList.add(new UmAndCustomerIdParam("qiuxie002","a002")); paramList.add(new UmAndCustomerIdParam("qiuxie002","a002")); paramList.add(new UmAndCustomerIdParam("qiuxie002","a002")); paramList.add(new UmAndCustomerIdParam("qiuxie002","a002")); Set<String> collect = paramList.stream().map(UmAndCustomerIdParam::getOcmCustId).collect(Collectors.toSet()); System.out.println(collect);
List<String> aList = dealStringList(); List<String> collect = aList.stream().map(a -> a.replaceAll(",", "")).collect(Collectors.toList()); collect.forEach(a -> { System.out.println(a); });
flatMap将每个值都转换成流
List<String> aList = dealStringList(); List<String> collect = aList.stream().flatMap(a -> { String[] split = a.split(","); Stream<String> stream = Arrays.stream(split); return stream; }).collect(Collectors.toList()); System.out.println(collect);
count 返回流中元素的总个数
List<Integer> queryList = queryList(); long count = queryList.stream().count(); System.out.println("集合中的元素数量:" + count);
max 返回最大值
List<Integer> queryList = queryList(); Integer integer = queryList.stream().max(Integer::compareTo).get(); System.out.println("最大元素:" + integer);
min 返回最小值
List<Integer> queryList = queryList(); Integer integer = queryList.stream().min(Integer::compareTo).get(); System.out.println("最小元素:" + integer);