Stream是jdk1.8的新特性,可以结合lambda表达式使用提升开发的效率和性能。
集合(List,Set)===(数组 ,map)
package com.wcf.stream; import com.wcf.pojo.Category; import java.util.ArrayList; import java.util.List; /** * @author 胡萝卜 * @createTime 2021/9/21 17:08 */ public class StreamDemo01 { public static void main(String[] args) { //创建一个List集合 List<Category> categoryList=new ArrayList<>(); categoryList.add(new Category(1L,"Java","Java",0L,1)); categoryList.add(new Category(2L,"Php","Php",0L,2)); categoryList.add(new Category(3L,"JavaScript","JavaScript",0L,3)); categoryList.add(new Category(4L,"Python","Python",0L,10)); categoryList.add(new Category(5L,"Go","Go",0L,8)); categoryList.add(new Category(6L,"Ruby","Ruby",0L,4)); } }
//stream完成排序 List<Category> categories = categoryList.stream().sorted(new Comparator<Category>() { @Override public int compare(Category o1, Category o2) { return o1.getSort() - o2.getSort(); } }).collect(Collectors.toList()); //打印 categories.forEach(System.out::println); } }
//过滤filter 过滤是把过滤条件满足的找到 List<Category> categories = categoryList.stream().filter(cate -> cate.getId().equals(2L)).collect(Collectors.toList()); //打印 categories.forEach(System.out::println);
//map改变集合中每个元素的信息 List<Category> categories = categoryList.stream().map(cate -> { cate.setSubtitle(cate.getSubtitle()+"yy"); return cate; }).collect(Collectors.toList()); //打印 categories.forEach(System.out::println);
//求总数 long count = categoryList.stream().count(); System.out.println(count);
//循环遍历 categoryList.stream().forEach(category -> { System.out.println(category); });
//distinct可以去重元素,如果集合是对象,如果要distinct,就对象要返回相同的hashcode和equals是true List<Category> categories = categoryList.stream().distinct().collect(Collectors.toList()); categories.forEach(System.out::println);
//求最大 Optional<Category> optionalCategory = categoryList.stream().max(new Comparator<Category>() { @Override public int compare(Category o1, Category o2) { return o1.getSort() - o2.getSort(); } }); if (optionalCategory.isPresent()){ System.out.println(optionalCategory.get()); }