Stream流的常用方法

前言

使用Stream流的时候一定要注意判断是否null。

forEach遍历

forEach:该方法接收一个Consumer接口函数,将每一个流元素交给该函数处理forEach方法:用来遍历流中的数据
注:是一个终结方法,遍历之后就不能继续调用Stream流中的其他方法

public class Stream_ForEach {
    public static void main(String[] args) {
        //获取一个Stream流
        Stream<String>stream= Stream.of("张三","李四","王五","赵六");
        //使用Stream流的方法forEach对stream流中的数据遍历
        //遍历stream1
        stream1.forEach((name)-> System.out.println(name));
        //输出stream2
        //stream1.stream().forEach(System.out::println);
    }
}
结果:
张三
李四
王五
赵六

filter过滤

filter:用于对Stream流中的数据进行过滤
filter(Predicatepredicate)
filter方法的参数Predicate是一个函数式接口,可以使用lambda表达式
Predicate中的抽象方法
boolean test(T t)

public class Stream_filter {
    public static void main(String[] args) {
        //创建一个Stream流
        Stream<String> stream = Stream.of("张三", "李四", "王五", "赵六1", "田七", "田七1");
 
        //单条件过滤
        Stream<String> stream1 = stream.filter((String name) -> {
            return name.startsWith("田");
        });
        //遍历stream1
        stream1.forEach((name)-> System.out.println(name));    
    }
}
结果:
田七
田七1

distinct去重

public class Stream_distinct {
    public static void main(String[] args) {
        //创建一个Stream流
        Stream<String> stream = Stream.of("张三", "张三","张三","李四", "王五", "赵六", "田七");
        //去重
        List<String> stream1 = stream.distinct().collect(Collectors.toList());
        //输出stream1
        System.out.println(stream1)
    }
}
结果:[张三, 李四, 王五, 赵六, 田七]

limit截取

limit:用于截取流中的元素
limit可以对流进行截取,只取用前n个
limit(long maxSize);
参数是一个long型,如果集合当前长度大于参数则进行截取,否则不进行操作
limit是一个延迟方法,可以继续使用Stream流方法

public class Stream_limit {
    public static void main(String[] args) {
        //创建一个集合
        ArrayList<String> list = new ArrayList<>(Arrays.asList("张三", "张三","张三","李四", "王五", "赵六1", "田七"));
        //截取去重后的前2个元素
        List<String> collect = list.stream().limit(2).collect(Collectors.toList());
        //输出stream1
        System.out.println(collect);
    }
}
结果:[张三, 张三]

skip跳过

skip方法:用于跳过元素
skip(long n)
如果流的当前长度大于n,则跳过前n个,否则将会得到一个长度为0的空流

public class Stream_skip {
    public static void main(String[] args) {
        //创建一个Stream流
        Stream<String> stream = Stream.of("张三","李四", "王五", "赵六", "田七");
        //跳过去重后的前2个元素
        List<String> collect = stream.skip(2).collect(Collectors.toList());
        //输出stream1
        System.out.println(collect);
    }
}
结果:[王五, 赵六, 田七]

排序sorted

public class Stream_sorted {
    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        list.add(new User(1,"张三",23));
        list.add(new User(2,"李四",18));
        list.add(new User(3,"王五",20));
        list.add(new User(4,"赵六",25));

        //根据年龄从小到大排序
        list = list.stream()
            .sorted(Comparator.comparing(User::getAge))
            .collect(Collectors.toList());
        list.forEach(System.out::println);
    }
}
结果:
User(id=2, name=李四, age=18)
User(id=3, name=王五, age=20)
User(id=1, name=张三, age=23)
User(id=4, name=赵六, age=25)

最值max,min

public class Stream_max_min {
    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        list.add(new User(1,"张三",23));
        list.add(new User(2,"李四",18));
        list.add(new User(3,"王五",20));
        list.add(new User(4,"赵六",25));
        //获取年龄最大的人
        User maxPeople = list.stream().max(Comparator.comparing(User::getAge)).get();

        //获取年龄最小的人
        User minPeople = list.stream().min(Comparator.comparing(User::getAge)).get();

        System.out.println(maxPeople);
        System.out.println(minPeople);
    }
}

统计reduce

public class Stream_reduce {
    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        list.add(new User(1,"张三",23));
        list.add(new User(2,"李四",18));
        list.add(new User(3,"王五",20));
        list.add(new User(4,"赵六",25));
        //计算所有用户的年龄的总和
        Integer reduce = list.stream().map(user -> user.getAge()).reduce(0, (a, b) -> a + b);

        System.out.println(reduce);
    }
}

List结构转换Map结构

把list信息转成map信息,方便使用k-v结构,使用其中ID,查询用户的全部信息,不用去遍历list取获取

public class Stream_list_to_map {
    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        list.add(new User(1,"张三",23));
        list.add(new User(2,"李四",18));
        list.add(new User(3,"王五",20));
        list.add(new User(4,"赵六",25));
        //方法一:List结构转换Map结构
        Map<Integer, User> userMap = list.stream().collect(Collectors.toMap(User::getId, user -> user));
    	//方法二:List结构转换Map结构
        Map<Integer, User> collect = list.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        System.out.println(userMap);
    }
}

List对象转List
提取一个对象里面的数据,进行其他的操作(比如提取用户的ID,取查询关联的信息)

 
public class Stream_object_string {
    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        list.add(new User(1,"张三",23));
        list.add(new User(2,"李四",18));
        list.add(new User(3,"王五",20));
        list.add(new User(4,"赵六",25));

        //提取用户的ID
        List<Integer> collect = list.stream().map(User::getId).collect(Collectors.toList());

        System.out.println(collect);
    }
}

List对象转List

把一个list中的对象转成另一个list中的对象

public class Stream_object_object {
    public static void main(String[] args) {
        List<People> peopleList = new ArrayList<People>();
        peopleList.add(new People("张三",23,new BigDecimal("3000"),new BigDecimal("1.1")));
        peopleList.add(new People("李四",24,new BigDecimal("2800"),new BigDecimal("1.2")));
        peopleList.add(new People("王五",22,new BigDecimal("3200"),new BigDecimal("1.3")));
        //对象转对象
        List<Student> studentList = peopleList.stream().map(s->{
            return new Student(s.getName(),s.getAge());
        }).collect(Collectors.toList());
        System.out.println("value:"+studentList);
    }
}

anyMatch匹配

anyMatch()主要用于判断流中是否至少存在一个符合条件的元素,它会返回一个boolean值,并且对于它的操作, 一般叫做短路求值

public class Stream_anyMatch {public static void main(String[] args) {
        //判断集合中是否有年龄小于20的学生
        List<User> list = new ArrayList<>();
        list.add(new User(1,"张三",23));
        list.add(new User(2,"李四",18));
        list.add(new User(3,"王五",20));
        list.add(new User(4,"赵六",25));
        
        if(list.stream().anyMatch(user -> user.getAge() < 20)){
            System.out.println("集合中有年龄小于20");
        }else {
            System.out.println("集合中没有年龄小于20");
        }
    }
}

allMatch匹配

allMatch()的工作原理与anyMatch()类似,但是anyMatch执行时,只要流中有一个元素符合条件就会返回true, 而allMatch会判断流中是否所有条件都符合条件,全部符合才会返回true

public class Stream_allMatch {public static void main(String[] args) {
        //判断集合中所有的年龄是否都小于20
         List<User> list = new ArrayList<>();
        list.add(new User(1,"张三",23));
        list.add(new User(2,"李四",18));
        list.add(new User(3,"王五",20));
        list.add(new User(4,"赵六",25));if(list.stream().allMatch(user -> user.getAge() < 20)){
            System.out.println("集合所有的年龄都小于20");
        }else {
            System.out.println("集合中有年龄大于20的");
        }
    }
}

findAny查找

findAny用于获取流中随机的某一个元素,并且利用短路在找到结果时,立即结束

public class Stream_findAny {
    public static void main(String[] args) {
        //findAny用于获取流中随机的某一个元素,并且利用短路在找到结果时,立即结束
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student(1,19,"张三1","M",true));
        students.add(new Student(1,18,"张三2","M",false));
        students.add(new Student(1,21,"张三3","F",true));
        students.add(new Student(1,20,"张三4","F",false));
        students.add(new Student(1,20,"张三5","F",false));
        students.add(new Student(1,20,"张三6","F",false));
        Optional<Student> student1 = students.stream().filter(student -> student.getSex().equals("F")).findAny();
        System.out.println(student1.toString());
    }
}
结果:Optional[Student{id=1, age=21, name='张三3', sex='F', isPass=true}]
这里的结果是sex=F的第一个元素,当为串行流且数据较少时,获取的结果一般为流中第一个元素,但是当为并流行的时候,则会随机获取。

findFirst查找

findFirst使用原理与findAny类似,只是它无论串行流还是并行流都会返回第一个元素。

public class Stream_findFirst {
    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student(1,19,"张三1","M",true));
        students.add(new Student(1,18,"张三2","M",false));
        students.add(new Student(1,21,"张三3","F",true));
        students.add(new Student(1,20,"张三4","F",false));
        students.add(new Student(1,20,"张三5","F",false));
        students.add(new Student(1,20,"张三6","F",false));
        Optional<Student> student1 = students.stream().filter(student -> student.getSex().equals("F")).ndFirst();
        System.out.println(student1.toString());
    }
}

收集齐中joining() 方法

public class Stream_joining {
    public static void main(String[] args) {
       List<String> list = Arrays.asList("Ram","Shyam","Shiv","Mahesh");
        String result = list.stream().collect(Collectors.joining());
        System.out.println(result);
        result = list.stream().collect(Collectors.joining(","));
        System.out.println(result);        
        result = list.stream().collect(Collectors.joining("-","[","]"));
        System.out.println(result);  
    }
}
运行结果为:
RamShyamShivMahesh
Ram,Shyam,Shiv,Mahesh
[Ram-Shyam-Shiv-Mahesh] 

对集合按照单个属性分组、分组计数、排序Collectors.groupingBy()

public class Stream_groupingBy {
    public static void main(String[] args) {
		Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya");
        // 分组
        Map<String, List<String>> result1 = items.stream().collect(Collectors.groupingBy(Function.identity()));
        System.out.println(result1);
    }
}
结果://{papaya=[papaya], orange=[orange], banana=[banana, banana], apple=[apple, apple, apple]}

单个属性分组

public class Stream_groupingBy {
	 public static void main(String[] args) {
		User user1 = new User(1L,"zhangSan",23, "[email protected]", 1,1L);
        User user2 = new User(2L,"lisi",24, "[email protected]", 1,1L);
        User user3 = new User(3L,"wanger",23, "[email protected]", 1,1L);
        User user4 = new User(4L,"zhaoliu",20, "[email protected]", 1,1L);
        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        Map<Integer, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getAge));
        System.out.println(collect);
     }
}
结果://{20=[User(id=4, name=zhaoliu, age=20, [email protected], deleted=1, depId=1)], 23=[User(id=1, name=zhangSan, age=23, [email protected], deleted=1, depId=1), User(id=3, name=wanger, age=23, [email protected], deleted=1, depId=1)], 24=[User(id=2, name=lisi, age=24, [email protected], deleted=1, depId=1)]}

分组计数

public class Stream_groupingBy {
    public static void main(String[] args) {
		Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya");
        // 计数
        Map<String, Long> result2 = items.stream().collect(
                Collectors.groupingBy(
                        Function.identity(), Collectors.counting()
                )
        );  
        System.out.println(result1);
    }
}
结果://{papaya=1, orange=1, banana=2, apple=3} 

你可能感兴趣的:(java,开发语言,java18,stream)