With all due respect, I doubt you’ve used Stream much

Are we the same?

Back then, xiaobian in self-learning Java language reading, about”The Stream flow“This is probably all a little bit of knowledge.”qinghua“Feel this piece of content”so easy“Very simple, a glance.

Little do they know, picked up sesame, lost watermelon; There’s never been a “Stream” status in small code; “Who the hell is that?” sneers Stream, the creator of java8.

For example, it’s been two years since I learned how to implement multithreading. This is also a SAO operation for a serial for loop

Java 8?

In Java 8, thanks to the functional programming of Lambda, a new concept, Stream, was created to solve the problems of the existing collection libraries.

First of all,

Operations on a Stream can be broadly divided into two types:

  • Intermediate operations, which return a Stream, can be stacked with multiple Intermediate operations.
  • Terminal operation, whose return result is the data we finally need, so there can only be one Terminal operation

The second

A Stream is a queue of elements from a data source, for example

  • Elements are objects of a specific type that form a queue. A Stream in Java does not store elements, but evaluates them on demand.
  • Data source Indicates the source of the flow. It could be collections, arrays, etc.

moreover

The Stream operation differs from the previous Collection operation in that it has two basic characteristics:

  • Pipelining: All intermediate operations return the flow object itself. These operations can be cascaded into a pipe, as in fluent style. This allows you to optimize operations, such as delay and short-circuiting.
  • Internal iteration: Previously, collections were iterated explicitly outside the collection by Iterator or enhanced for. This is called external iteration. A Stream provides a way to iterate internally, and a Stream can call the traversal method directly.

The last

Take a look at the Stream interfaceInheritance relationships So, when we use a stream, there are usually three basic steps:Get a data source → Data transformation → Perform the operation to get the desired result

However, each conversion does not change the original Stream object and returns a new Stream object (which can have multiple conversions), allowing operations on it to be arranged like a chain and become a pipe.

Note that a “Stream” is a functional model of collection elements. It is not a collection, nor is it a data structure, and does not store any elements (or their address values) on its own.

Therefore, Stream’s dominant position is not without reason

Next, hardcoreSoa operationsDon’t blink of an eye,

Why do WE need a Stream

Doesn’t it smell good? Why Stream?

Here’s a simple example:

Students:

@Data
@AllArgsConstructor
public class Student {

    @apiModelProperty (value = "name ")
    private String name;

    @apiModelProperty (value = "age ")
    private Integer age;

    @apiModelProperty (value = "gender (1-male, 2-female)")
    private Integer sex;
}
Copy the code

Collection of student Objects

public class StreamDemo {

    public static void main(String[] args) {
		// Test data
        List<Student> studentList = Lists.newArrayList();
        studentList.add(new Student("CodeCow".18.1));
        studentList.add(new Student("Xiao Ming".30.1));
        studentList.add(new Student("Pig".40.2));
        studentList.add(new Student("Puppy Dog".50.2)); }}Copy the code

Suppose, existing requirements: screen all students with the surname of small, and the name has three characters, and finally print out the result

I’m very lucky to have seen such SAO code, which can be described as “the Dragon is crossing the River”.

public static void main(String[] args) {

    // Step 1: select the student whose surname is small and place it in list1
    List<Student> list1 = Lists.newArrayList();
    for (Student student : studentList) {
        if (student.getName().startsWith("Small")) { list1.add(student); }}// Step 2: select the student whose name has three characters and place it on list2
    List<Student> list2 = Lists.newArrayList();
    for (Student student : list1) {
        if (student.getName().length() == 3) { list2.add(student); }}// Step 3: Print the result
    for(Student student : list2) { System.out.println(student); }}Copy the code

Next, we run Debug to see the result:

Student(name= dog, age=50, sex=2)
Copy the code

But now there are only three conditions for the contest. When there are dozens of conditions, there are dozens of for cycles.

In addition, you will have Java 8’s elder brother – stream, as to where

Experience a better way to write a ha Stream

I’m sure you all know Lambda. Lambda in Java 8 allows us to focus more on What rather than How.

This point is also small series in the last article “two years, just know how to implement multi-threading, ah” combined with “threads + anonymous inner class” for comparison.

Now, let’s experience the elegance of a Stream:

public static void main(String[] args) {

   studentList.stream()
   		.filter(i -> i.getName().startsWith("Small"))// Filter out students whose surname is small
        .filter(i -> i.getName().length() == 3) // Filter out students whose names have three characters
        .forEach(System.out::println); // Print the result
}
Copy the code

Run Debug again and see the result:

Student(name= dog, age=50, sex=2)
Copy the code

It’s not hard to see that three lines of code will do the same; At the same time, by the way, the SAO operation above is solved. Isn’t he fragrant?

To summarize, why does it smell good

  • First point: we can clearly know what we want to do with a data set, which is very readable.
  • Second point: you can easily get parallel streams without having to write your own multithreaded code (as evidenced by the previous article!!).
  • Third point: it allows us to focus more on our business logic (think of a few for loops!!). .

In short, Stream, in love, in love

Do you think that’s what a Stream is all about? “No, No, No”

Next, let’s look at the Stream Stream SAO collection

Learn more about THE SAO operations on Stream streams

Requirement 1: Get a collection of students with last names

public static void main(String[] args) {

    List<Student> list = studentList.stream()
    	.filter(i -> i.getName().startsWith("Small"))
    	.collect(Collectors.toList());
}
Copy the code

The result is:

[Student(name= name, age= age30, sex=1), Student(name= pig, age=40, sex=2), Student(name= dog, age=50, sex=2)]Copy the code

Requirement 2: Get the set of students whose last name is younger than 30

public static void main(String[] args) {

    List<Student> list = studentList.stream()
    	.filter(i -> i.getName().startsWith("Small") && i.getAge() >30)
    	.collect(Collectors.toList());
}
Copy the code

The result is:

[Student(name= pig, age=40, sex=2), Student(name= dog, age=50, sex=2)]Copy the code

Requirement 3: Get the set of students whose name is “Xiao Ming”

public static void main(String[] args) {

    List<Student> list = studentList.stream()
    	.filter(i -> i.getName().equals("Xiao Ming"))
    	.collect(Collectors.toList());
}
Copy the code

The result is:

[Student(name= name, age= age40, sex=1)]
Copy the code

Requirement 4: Get a collection of all students’ names

public static void main(String[] args) {

    List<String> list = studentList.stream()
    	.map(Student::getName)
        .collect(Collectors.toList());
}
Copy the code

The result is:

[CodeCow, Xiao Ming, Little Pig, little dog]Copy the code

Requirement 5: Sort students in ascending order by age

public static void main(String[] args) {

    List<Student> list = studentList.stream()
    	.sorted(Comparator.comparing(Student::getAge))
    	.collect(Collectors.toList());
}
Copy the code

The result is:

[
Student(name=CodeCow, age=18, sex=1), Student(name= xiaoming, age=40, sex=1), Student(name= pig, age=50, sex=2), Student(name= dog, age=50, sex=2)]Copy the code

Requirement 6: Sort students in descending order by age

public static void main(String[] args) {

    List<Student> list = studentList.stream()
    	.sorted(Comparator.comparing(Student::getAge).reversed())
    	.collect(Collectors.toList());
}
Copy the code

The result is:

[Student(name= pig, age=50, sex=2), Student(name= dog, age=50, sex=2), Student(name= xiaoming, age=40, sex=1), 
Student(name=CodeCow, age=18, sex=1)]Copy the code

Requirement 7: Distinct deduplication

public static void main(String[] args) {

	List<Integer> integers = Lists.list(30.40.10.20.20.10.50.20);
    List<Integer> collect = 
    		integers.stream().distinct().collect(Collectors.toList());
    System.out.println(collect);//[30, 40, 10, 20, 50
}
Copy the code

Requirement 8: Find the minimum min, total quantity count

public static void main(String[] args) {

	List<Integer> integers = Lists.list(30.40.10.20.20.10.50.20);
	Integer integer1 = integers.stream().min(Integer::compareTo).orElse(-1);
	    System.out.println(integer1); / / 10 min
	    long count = integers.stream().count();
	    System.out.println(count);/ / the total number 8
}
Copy the code

Shallow talkJava 8 Stream flow, that’s all for now, see ^_^ below

Afterword.

Java 8 Stream Java 8 Stream Java 8 Stream And not all of the features of Stream, just the tip of the iceberg; See below ^_^

★★ Good article recommendation ★★

  • Two years, just know how to implement multithreading, ah
  • Promise me no more if/else validation of request parameters, okay
  • Chat filter + interceptor + JWT
  • Wechat mini program payment + public account payment (including source code)
  • Wechat official account authorization + access to user information + JWT login (source code included)
  • Wechat mini program authorization + obtaining user’s mobile phone number + JWT login (source included)

★★ whisper BB ★★

  • Chinese traditional culture, first carefully, if useful, and then click “like” or “collect”, give yourself a little time to think
  • If you don’t understand, you can leave a comment or write a private letter to make up, and make up will reply to ^_^ in the first time
  • More humorous, witty articles, all in the “CodeCow· program cow” public account

“Java is like the sea, learn to make a boat, sailing on the sea, know the breadth of Java”