ds1:java-stream stream


The link to the study text of this article: http://t.csdn.cn/tjweo

1. Modify the value map in the collection

Pass in a function, the formal parameter of the function is each value in the collection, the function will perform the operation in the function body on each element in the collection, and finally return a new value, modify or replace the elements in the
collection For two cases: directly modify the data in the original collection and generate a new collection.

Advanced gameplay: You can directly pass in Student::getAge or personList.stream().map(p -> p.getAge()) in the map to get all the ages of all objects in the collection, and then operate on the attributes in a chain. The return value is also changed from the object type in the collection to the corresponding attribute type of the object.

		//直接修改原来的数据 所有学生的年龄加2
        List<Student> list1 = Arrays.asList(new Student("a",1),new Student("b",2),new Student("c",3));
        List<Student> studentAgeAdd1 = list1.stream().map(x -> {
    
    
            x.setAge(x.getAge() + 2);
            return x;
        }).collect(Collectors.toList());
        System.out.println("list1 = " + list1);
        System.out.println("studentAgeAdd1 = " + studentAgeAdd1);

		//生成新的集合 所有学生的年龄加2
        List<Student> list2 = Arrays.asList(new Student("a",1),new Student("b",2),new Student("c",3));
        List<Student> studentAgeAdd2 = list2.stream().map(x -> {
    
    
            return new Student(x.getUsername(), x.getAge()+2);
        }).collect(Collectors.toList());
        System.out.println("list2 = " + list2);
        System.out.println("studentAgeAdd2 = " + studentAgeAdd2);
//结果
Student(username=null, age=null)
list1 = [Student(username=a, age=3), Student(username=b, age=4), Student(username=c, age=5)]
studentAgeAdd1 = [Student(username=a, age=3), Student(username=b, age=4), Student(username=c, age=5)]
list2 = [Student(username=a, age=1), Student(username=b, age=2), Student(username=c, age=3)]
studentAgeAdd2 = [Student(username=a, age=3), Student(username=b, age=4), Student(username=c, age=5)]

2. Filter the eligible values ​​in the collection filter

Pass in a function, the formal parameter of the function is each value in the collection, the function will perform operations on each element in the collection in the function body, the function body is a conditional judgment, and finally returns a boolean value, which is true Keep the element as , and remove it if false. Finally generate a new collection. The original collection is not changed.

		//保留年龄大于等于3的学生
        List<Student> list1 = Arrays.asList(new Student("a",1),new Student("b",2),new Student("c",3));
        List<Student> studentAgeAdd1 = list1.stream().filter((x) -> {
    
    
            return x.getAge() >= 2;
        }).collect(Collectors.toList());
        System.out.println("list1 = " + list1);
        System.out.println("studentAgeAdd1 = " + studentAgeAdd1);

Find the largest/smallest value in the collection, and the number of elements after the operation max()/min()/count()

list.stream().max().get();
list.stream().min().get();
list.stream().filter().count();//The number after operation

		//获取学生年龄最大的那个
        List<Student> list1 = Arrays.asList(new Student("a",1),new Student("b",2),new Student("c",3));
        Student student = list1.stream().max(Comparator.comparing(Student::getAge)).get();
        Student student1 = list1.stream().max((a, b) -> {
    
    
            return a.getAge() - b.getAge();
        }).get();
        System.out.println(student);
        System.out.println(student1);

//输出
Student(username=c, age=3)
Student(username=c, age=3)
		
		//统计过滤后的数量
        List<Student> list1 = Arrays.asList(new Student("a",1),new Student("b",2),new Student("c",3));
        long count = list1.stream().filter(x -> x.getAge() >= 2).count();
//输出
2

Reduction: Perform custom calculations on all elements in the collection to obtain the final value reduce()

reduce 、

		//将所有对象中某元素的值相加
        List<Student> list1 = Arrays.asList(new Student("a",1),new Student("b",2),new Student("c",3));
        Integer sumAge = list1.stream().map(Student::getAge).reduce(Integer::sum).get();
        System.out.println(sumAge);

		//获取集合中所有元素和
        List<Integer> intList = Arrays.asList(1, 2, 3);
        Integer integer = intList.stream().reduce((sum, item) -> {
    
    
            sum += item;
            return sum;
        }).get();
        System.out.println(integer);

collect

The stream does not store data, so after the data in the stream is processed, the data in the stream needs to be regrouped into a new collection.
toList/toSet/toMap
example: list->map

        List<Student> list1 = Arrays.asList(new Student("a",1),new Student("b",2),new Student("c",3));
        Map<String, Student> collect = list1.stream().collect(Collectors.toMap(Student::getUsername, p -> p));
        for (Map.Entry<String, Student> studentEntry : collect.entrySet()) {
    
    
            System.out.println(studentEntry);
        }
//打印
a=Student(username=a, age=1)
b=Student(username=b, age=2)
c=Student(username=c, age=3)

Collectors provide a series of static methods for data statistics:
Counting: count
Average: averagingInt, averagingLong, averagingDouble
Maximum value: maxBy, minBy
Summing: summingInt, summingLong, summingDouble
Statistics above all: summarizingInt, summarizingLong, summarizingDouble (including counting , average, maximum, and)

insert image description here

Grouping (partitioningBy/groupingBy)

partitioningBy(): Conditional grouping
groupingBy(): Grouping according to the same elements in the collection

public class StreamTest {
    
    
	public static void main(String[] args) {
    
    
		List<Person> personList = new ArrayList<Person>();
		personList.add(new Person("Tom", 8900, "male", "New York"));
		personList.add(new Person("Jack", 7000, "male", "Washington"));
		personList.add(new Person("Lily", 7800, "female", "Washington"));
		personList.add(new Person("Anni", 8200, "female", "New York"));
		personList.add(new Person("Owen", 9500, "male", "New York"));
		personList.add(new Person("Alisa", 7900, "female", "New York"));

		// 将员工按薪资是否高于8000分组
        Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
        // 将员工按性别分组
        Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));
        // 将员工先按性别分组,再按地区分组,嵌套分组
        Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
        System.out.println("员工按薪资是否大于8000分组情况:" + part);
        System.out.println("员工按性别分组情况:" + group);
        System.out.println("员工按性别、地区:" + group2);
	}
}


//输出结果
员工按薪资是否大于8000分组情况:{
    
    false=[mutest.Person@2d98a335, mutest.Person@16b98e56, mutest.Person@7ef20235], true=[mutest.Person@27d6c5e0, mutest.Person@4f3f5b24, mutest.Person@15aeb7ab]}
员工按性别分组情况:{
    
    female=[mutest.Person@16b98e56, mutest.Person@4f3f5b24, mutest.Person@7ef20235], male=[mutest.Person@27d6c5e0, mutest.Person@2d98a335, mutest.Person@15aeb7ab]}
员工按性别、地区:{
    
    female={
    
    New York=[mutest.Person@4f3f5b24, mutest.Person@7ef20235], Washington=[mutest.Person@16b98e56]}, male={
    
    New York=[mutest.Person@27d6c5e0, mutest.Person@15aeb7ab], Washington=[mutest.Person@2d98a335]}}

Modify the connector join between elements in the collection

public class StreamTest {
    
    
	public static void main(String[] args) {
    
    
		List<Person> personList = new ArrayList<Person>();
		personList.add(new Person("Tom", 8900, 23, "male", "New York"));
		personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
		personList.add(new Person("Lily", 7800, 21, "female", "Washington"));

		String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));
		System.out.println("所有员工的姓名:" + names);
		List<String> list = Arrays.asList("A", "B", "C");
		String string = list.stream().collect(Collectors.joining("-"));
		System.out.println("拼接后的字符串:" + string);
	}
}

extract/combine

public class StreamTest {
    
    
	public static void main(String[] args) {
    
    
		String[] arr1 = {
    
     "a", "b", "c", "d" };
		String[] arr2 = {
    
     "d", "e", "f", "g" };

		Stream<String> stream1 = Stream.of(arr1);
		Stream<String> stream2 = Stream.of(arr2);
		// concat:合并两个流 distinct:去重
		List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
		// limit:限制从流中获得前n个数据
		List<Integer> collect = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
		// skip:跳过前n个数据
		List<Integer> collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());

		System.out.println("流合并:" + newList);
		System.out.println("limit:" + collect);
		System.out.println("skip:" + collect2);
	}
}

//输出
流合并:[a, b, c, d, e, f, g]
limit:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
skip:[3, 5, 7, 9, 11]

Guess you like

Origin blog.csdn.net/m0_56182317/article/details/131577505