java stream stream object summary

1, Introduction

Java8/JDK8 is the official version released by Oracle in 2014. I'm only now familiar with the features of java8. I really feel that I can't keep up with the rhythm!
Although feeling, it's still not too late. It's not an urging statement: as long as you are willing to start, it's never too late!
Let's study in blocks!

2, . stream()

A Stream is a queue of elements from a data source and supports aggregation operations

Stream does not store elements, but a series of operations
Source of stream: set, array, I/O channel, generator, etc
Aggregation operations: filter, map, reduce, find, match, sorted, etc.
Use. stream() to become a stream, and then perform a series of aggregation operations.
After creating a Stream, we can add various operations to the Stream. The following table lists all the operations supported by the Stream:

There are two ways to generate streams

stream() − creates a serial stream for the collection.
parallelStream() − creates a parallel stream for the collection.

3, Aggregate function

3.1 forEach

Stream provides a new method 'forEach' to iterate over each data in the stream.
The use of System.out::println in the code depends on this

3.2 map

The map method is used to map each element to the corresponding result. The following code snippet uses map to output the square corresponding to the element:

List<Integer> list = Arrays.asList(1,2,3,4,5);
list.stream().map(x->x*x).forEach(System.out::println);

Execution screenshot:

Application: take a value from the object to form a flow available map

List<SortData> sortDataList = new ArrayList<>();
SortData user1 = new SortData(100L);
SortData user2 = new SortData(200L);
sortDataList.add(user1);
sortDataList.add(user2);

sortDataList.stream().map(item -> item.getData()*100).forEach(System.out::println);

Effect screenshot:

Of course, the SortData object I created earlier is as follows:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class SortData implements Serializable {
    private Long  data;
}

3.3 filter

The filter method is used to filter out elements through the set conditions. The following code snippet uses the filter method to filter out empty strings:

@Test
public void filterTest() {
    List<String> list = Arrays.asList("a","","b","","cc","x","dd");
    System.out.println("Display after filtering:");
    list.stream().filter(item -> !item.trim().isEmpty()).forEach(System.out::println);
    System.out.println("Number before filtering:"+list.size());
    System.out.println("Number after filtering:"+list.stream().filter(item -> !item.trim().isEmpty()).count());
}

Operation effect:

3.4 limit

The limit method is used to get a specified number of streams.

List<String> list = Arrays.asList("a","","b","","cc","x","dd");
list.stream().limit(3).forEach(System.out::println);

Screenshot of operation effect: the first three are obtained

3.5 sorted

The sorted method is used to sort streams.

    @Test
    public void streamTest2() {
        List<Integer> list = Arrays.asList(1,3,4,2,6,2);
        List<Integer> collect = list.stream().sorted().collect(Collectors.toList());
        System.out.println("Stream Natural sorting");
        for (Integer i : collect) {
            System.out.print(i+" ");
        }
        List<Integer> collect2 = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        System.out.println(" ");
        System.out.println("Stream Reverse order");
        for (Integer i : collect2) {
            System.out.print(i+" ");
        }
        System.out.println(" ");
        System.out.println("List Reverse order");
        list.sort(((o1, o2) -> o1 > o2 ? -1 : 1));
        list.forEach(System.out::println);
    }

Operation effect

3.6 parallelStream

Parallel stream is an alternative to stream parallel processors.

@Test
public void parallelStreamTest() {
    List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
    // Gets the number of empty strings
    long count = strings.parallelStream().filter(string -> string.isEmpty()).count();
    System.out.println(count);
}

The results are as follows:

3.7 Collectors

The collectors class implements many reduction operations, such as converting streams into collections and aggregation elements. Collectors can be used to return lists or strings:

@Test
public void collectorsTest() {
    List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
    //Add an a to each non null character
    List<String> collect1 = strings.stream().filter(item -> !item.isEmpty()).map(item -> item + 'a').collect(Collectors.toList());
    System.out.println(collect1.toString());
    String collect2 = strings.stream().filter(item -> !item.isEmpty()).collect(Collectors.joining("#"));
    System.out.println(collect2);
}

Execution effect:

3.8 statistics

Some collectors that produce statistical results are very useful. They are mainly used for basic types such as int, double and long. They can be used to produce statistical results similar to the following.

@Test
public void totalStreamTest1() {
    List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5,12);
    IntSummaryStatistics intSummaryStatistics = numbers.stream().mapToInt(o->o).summaryStatistics();
    System.out.println("Average in list : " + intSummaryStatistics.getAverage());
    System.out.println("Number of in the list : " + intSummaryStatistics.getCount());
    System.out.println("Maximum number in list : " + intSummaryStatistics.getMax());
    System.out.println("Average in list : " + intSummaryStatistics.getMin());
    System.out.println("Total in list : " + intSummaryStatistics.getSum());
}

Operation effect:

4, Complex condition processing

4.1 group summation

@Test
public void groupAndSumTest() {
    List<SortData> list = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        SortData sortData = new SortData();
        sortData.setData(Math.round(Math.random()*100));
        sortData.setDataType("test"+i);
        list.add(sortData);
    }
    for (int i = 0; i < 10; i++) {
        SortData sortData = new SortData();
        sortData.setData(Math.round(Math.random()*100));
        sortData.setDataType("test"+i);
        list.add(sortData);
    }
    list.forEach(System.out::println);
    Map<String, LongSummaryStatistics> groupByType = list.stream().collect(Collectors.groupingBy(SortData::getDataType, Collectors.summarizingLong(SortData::getData)));
    System.out.println("Test 1:"+groupByType.get("Test 1"));
    System.out.println("Test 1 scores and:"+groupByType.get("Test 1").getSum());
    System.out.println("Maximum score in test 1:"+groupByType.get("Test 1").getMax());
    System.out.println("Minimum score in test 1:"+groupByType.get("Test 1").getMin());
    System.out.println("Average score in test 1:"+groupByType.get("Test 1").getAverage());
    System.out.println("Number of tests:"+groupByType.get("Test 1").getCount());
}

Operation results:

4.2 combined sorting

@Test
public void groupAndSortTest() {
    Student student1 = new Student("Xiao Hong", "female", 18,57);
    Student student2 = new Student("Small", "female", 21,67);
    Student student3 = new Student("Small is", "female", 35,79);
    Student student4 = new Student("Small", "female", 14,96);
    Student student5 = new Student("Ego", "male", 25,88);
    Student student6 = new Student("Small hair", "male", 32,88);
    Student student7 = new Student("Little give", "male", 16,88);
    Student student8 = new Student("Xiaohao", "male", 22,66);
    List<Student> list = new ArrayList<>();
    list.add(student1); list.add(student3); list.add(student5); list.add(student7);
    list.add(student2); list.add(student4); list.add(student6); list.add(student8);
    //In a class, everyone has their own scores. How to use code in java to sort everyone's scores first according to gender and then according to age.
    System.out.println("Combined sorting:");
    System.out.println("First:");
    List<Student> collectSortedMore = list.stream()
            .sorted(Comparator.comparing(Student::getSex).reversed()
                    .thenComparing(Student::getScore).reversed()
                    .thenComparing(Student::getAge).reversed())
            .collect(Collectors.toList());
    collectSortedMore.stream().forEach(System.out::println);
    System.out.println("Second:");
    list.sort(Comparator.comparing(Student::getSex).reversed()
            .thenComparing(Student::getScore).reversed()
            //The comparison between the two shows that. reversed() is used for the whole result set, not a single field
            .thenComparing(Student::getAge));
    list.stream().forEach(student -> System.out.println(student));
}

4.3 extreme value calculation

Scenario:
In a class, everyone has his own score. How to use code in java to find the average score, maximum score and minimum score of the class.

method:
First, use summarizingLong and summarizingInt to summarize the scores, and then obtain the extreme values respectively
Get average -- getAverage()
Get maximum -- getMax()
Get minimum value - getMin()
Get total score - getSum()
Get number -- getCount()

@Test
public void numTest() {
    Student student1 = new Student("Xiao Hong", "female", 18,57);
    Student student2 = new Student("Small", "female", 21,67);
    Student student3 = new Student("Small is", "female", 35,79);
    Student student4 = new Student("Small", "female", 14,96);
    Student student5 = new Student("Ego", "male", 25,65);
    Student student6 = new Student("Small hair", "male", 32,85);
    Student student7 = new Student("Little give", "male", 16,96);
    Student student8 = new Student("Xiaohao", "male", 22,66);
    List<Student> list = new ArrayList<>();
    list.add(student1); list.add(student3); list.add(student5); list.add(student7);
    list.add(student2); list.add(student4); list.add(student6); list.add(student8);
    System.out.println("Extreme value:");
    LongSummaryStatistics collectStudentsSummary = list.stream().collect(Collectors.summarizingLong(Student::getScore));
    System.out.println("average value=" + collectStudentsSummary.getAverage());
    System.out.println("number=" + collectStudentsSummary.getCount());
    System.out.println("Maximum=" + collectStudentsSummary.getMax());
    System.out.println("minimum value=" + collectStudentsSummary.getMin());
    System.out.println("the sum=" + collectStudentsSummary.getSum());

}

Result display:

Tags: Java

Posted on Tue, 28 Sep 2021 02:51:50 -0400 by myleow