This is my second day of the August Challenge

Introduction of the Stream

A Stream Stream is a new feature introduced in Java 8 for handling data in collections. It is a completely different concept from the InputStream and OutputStream in the Java.io package.

Stream is not a data structure and does not hold data. It is about algorithms and calculations, more like an advanced version of an Iterator. The original version of Iterator could only explicitly iterate over elements one by one and perform certain operations on them; The advanced version of Stream implicitly iterates through and converts the data as long as it tells you what to do with the elements it contains, such as “filter out strings larger than 10”, “determine whether to contain a character”, and so on.

The Stream API uses Lambda expressions, which are also new, to greatly improve programming efficiency and program readability. At the same time, it provides serial and parallel mode for aggregation operation, which makes it easy to write high-performance concurrent programs.

The use of the Stream

There are three types of stream operations:

(1) create flow

(2) Modify flow elements (Intermediate Operations)

(3) Consumption flow elements (Terminal Operations)

There are two ways to create a stream: (1) stream() : Create a serial stream. (2) parallelStream() : create a parallelStream.

In parallel flow, a large task is divided into several smaller tasks, which can be executed together without order. Of course, if we need to order output, we can use forEachOrdered output, which is faster than serial flow. It is possible to speed up your multi-threaded tasks by using the default ForkJoinPool.

(1) Convert elements into streams via stream.of ()

/ / the Stream of creating flow

Stream Stream = Stream. Of (” you “, “I “,” she “);

(2) Each collection can generate a stream by calling the stream() method

String [] strArray = new String[] {“a”, “b”, “c”};

stream = Stream.of(strArray);

stream = Arrays.stream(strArray);

List list = Arrays.asList(strArray);

stream = list.stream();

Set w = new HashSet<>(Arrays.asList(strArray))

stream = w.stream();

Using an example

The class used in the case

class Person { private String name; // Private int salary; // Private int age; // Private String sex; // Private String area; Public Person(String name, int salary, int age,String sex,String area) {this.name = name; this.salary = salary; this.age = age; this.sex = sex; this.area = area; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", salary=" + salary + ", age=" + age + ", sex='" + sex + '\'' + ", area='" + area + '\'' + '}'; }}Copy the code

Match (foreach/find/match)

Stream also supports iterating over and matching elements like collections, but the elements in a Stream are Optional. The Optional class is a null container object that will be returned by a call to get().

@Test public void streamTest1() { List<Person> personList = new ArrayList<Person>(); Personlist. add(new Person(" Naruto ", 8900, 18, "1"," helix ")); PersonList. Add (new Person(" sasaki ", 8800, 18, "1"," sasaki ")); Personlist. add(new Person(" Sakura ", 7800, 17, "2"," healing ")); Personlist. add(new Person(" ailiya ", 8200, 30, "1"," psychic ")); Personlist. add(new Person(" personList ", 9500, 30, "1"," personList ")); Personlist. add(new Person(" hand ", 7900, 29, "2"," Bahau ")); personList. Add (new Person(" hand ", 7900, 29, "2"," Bahau ")); Personlist.stream ().filter(person -> person.getSalary() > 8000).foreach (system.out ::println); // Match Optional<Person> findFirst = personList.stream().filter(Person -> person.getage () > 18).findFirst(); // Match Optional<Person> findFirst = personList.stream().filter(Person -> person.getage () > 18). System.out.println(" match first value: "+ findFirst.get())); / / match a random (applicable to parallel flow) Optional < Person > findAny = personList. ParallelStream () filter (Person - > Person. GetAge () > 18).findAny(); System.out.println(" match a random value: "+ findany.get ())); Boolean anyMatch = personList.stream().anymatch (person -> person.getage () > 20); System.out.println(" Are there any children older than 20: "+ anyMatch); }Copy the code

Running result:

(2) Filter

Filtering is an operation that verifies the elements in the flow according to certain rules and extracts the elements that meet the conditions into the new flow.

public void streamTest2() { List<Person> personList = new ArrayList<Person>(); Personlist. add(new Person(" Naruto ", 8900, 18, "1"," helix ")); PersonList. Add (new Person(" sasaki ", 8800, 18, "1"," sasaki ")); Personlist. add(new Person(" Sakura ", 7800, 17, "2"," healing ")); Personlist. add(new Person(" ailiya ", 8200, 30, "1"," psychic ")); Personlist. add(new Person(" personList ", 9500, 30, "1"," personList ")); Personlist. add(new Person(" hand ", 7900, 29, "2"," Bahau ")); personList. Add (new Person(" hand ", 7900, 29, "2"," Bahau "));Copy the code
List<Person> List = personlist.stream ().filter(Person -> person.getSalary() > 8000).collect(Collectors.toList()); System.out.println(" combat value greater than 8000: "+ list); }Copy the code

Running result:

(3) aggregation (Max /min/count/sum)

Max, min, count, and sum are all familiar words, yes, we use them in mysql for statistics. Java Stream also introduces these concepts and usage, greatly facilitates our collection, array data statistics work.

@Test public void streamTest3() { List<Person> personList = new ArrayList<Person>(); Personlist. add(new Person(" Naruto ", 8900, 18, "1"," helix ")); PersonList. Add (new Person(" sasaki ", 8800, 18, "1"," sasaki ")); Personlist. add(new Person(" Sakura ", 7800, 17, "2"," healing ")); Personlist. add(new Person(" ailiya ", 8200, 30, "1"," psychic ")); Personlist. add(new Person(" personList ", 9500, 31, "1"," personList ")); Personlist. add(new Person(" hand ", 7900, 29, "2"," Bahau ")); personList. Add (new Person(" hand ", 7900, 29, "2"," Bahau ")); // Get Optional<Person> Max = personlist.stream ().max(Comparator.comparing(Person::getAge)); // Get Optional<Person> Max = personlist.stream ().max(Comparator.comparing(Person::getAge)); System.out.println(" the oldest is: "+ max.get()); // Optional<Person> min = personlist.stream ().min(Comparator.comparing(Person::getSalary)); System.out.println(" the least effective is: "+ min.get())); Long count = personlist.stream ().filter(person -> person.getSalary() > 8000).count(); System.out.println(" the number of combat forces greater than 8000 is: "+ count); Int sum = personlist.stream ().maptoint (person -> person.getage ()).sum(); System.out.println(" total age is: "+ sum); }Copy the code

Running result:

(4) sorted (3) sorted

There are two kinds of ordering in stream:

Sorted () : Natural sort where elements in the stream need to implement the Comparable interface

Sorted (Comparator com) : Specifies a custom sort. Specifies a custom Comparator

@Test public void streamTest4() { List<Person> personList = new ArrayList<Person>(); Personlist. add(new Person(" Naruto ", 8900, 18, "1"," helix ")); PersonList. Add (new Person(" sasaki ", 8800, 18, "1"," sasaki ")); Personlist. add(new Person(" Sakura ", 7800, 17, "2"," healing ")); Personlist. add(new Person(" ailiya ", 8200, 30, "1"," psychic ")); Personlist. add(new Person(" personList ", 9500, 31, "1"," personList ")); Personlist. add(new Person(" hand ", 7900, 29, "2"," Bahau ")); personList. Add (new Person(" hand ", 7900, 29, "2"," Bahau ")); List<Person> newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).collect(Collectors.toList()); System.out.println(" order by combat power in ascending order: "+ newList); List<Person> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).collect(Collectors.toList()); System.out.println(" order by combat power descending: "+ newList2); List<Person> newList3 = personlist.stream ().sorted((p1, 1); p2) -> { if (p1.getAge() == p2.getAge()) { return p2.getSalary() - p1.getSalary(); } else { return p2.getAge() - p1.getAge(); } }).collect(Collectors.toList()); System.out.println(" by age then by combat power: "+ newList3); }Copy the code

Running result:

(5) Map /flatMap

Mapping, which maps elements of one stream to another according to certain mapping rules. There are map and flatMap:

Map: Takes a function as an argument that is applied to each element and mapped to a new element.

FlatMap: Takes a function as an argument, replaces each value in a stream with another stream, and then connects all streams into one.

public void streamTest5() { List<Person> personList = new ArrayList<Person>(); Personlist. add(new Person(" Naruto ", 8900, 18, "1"," helix ")); PersonList. Add (new Person(" sasaki ", 8800, 18, "1"," sasaki ")); Personlist. add(new Person(" Sakura ", 7800, 17, "2"," healing ")); Personlist. add(new Person(" ailiya ", 8200, 30, "1"," psychic ")); Personlist. add(new Person(" personList ", 9500, 31, "1"," personList ")); Personlist. add(new Person(" hand ", 7900, 29, "2"," Bahau ")); personList. Add (new Person(" hand ", 7900, 29, "2"," Bahau "));Copy the code
// Combine character and kill skill,  List<String> strList = personList.stream().map(person -> person.getName() + "-->" + person.getArea()).collect(Collectors.toList()); System.out.println(" character and skill combo: "+ strList); }Copy the code

Running result:

(6) Reduce

Reduction, also known as reduction, is the reduction of a stream to a value that enables summing, multiplying, and maximizing the set.

@Test public void streamTest6() { List<Person> personList = new ArrayList<Person>(); Personlist. add(new Person(" Naruto ", 8900, 18, "1"," helix ")); PersonList. Add (new Person(" sasaki ", 8800, 18, "1"," sasaki ")); Personlist. add(new Person(" Sakura ", 7800, 17, "2"," healing ")); Personlist. add(new Person(" ailiya ", 8200, 30, "1"," psychic ")); Personlist. add(new Person(" personList ", 9500, 31, "1"," personList ")); Personlist. add(new Person(" hand ", 7900, 29, "2"," Bahau ")); personList. Add (new Person(" hand ", 7900, 29, "2"," Bahau ")); 1 Integer sum = personList.stream().map(Person::getSalary).reduce((x,y) -> x + y).get(); System.out.println(" sum of combat power (mode 1) : "+ sum); Integer sum2 = personList.stream().map(Person::getSalary).reduce(Integer::sum).get(); System.out.println(" sum of combat effectiveness (mode 2) : "+ sum2); 3 Integer sum3 = personList.stream().map(Person::getSalary).reduce(0,Integer::sum); System.out.println(" sum of combat effectiveness (mode 3) : "+ sum3); Integer product = personList.stream().map(Person::getAge).reduce((x,y) -> x * y).get(); System.out.println(" age: "+ product); Integer Max = personList.stream().map(Person::getSalary).reduce(1,Integer:: Max); System.out.println(" Max: "+ Max); }Copy the code

Running result:

(7) Collect

Collection, can be said to be the most diverse, the most functional part. Literally, a stream is collected, either as a value or as a new set. Mainly rely on Java. Util. Stream. Collectors class built-in static methods.

(8) Collection (toList/toSet/toMap)

Because streams do not store data, the data in the stream needs to be reassembled into new collections after the data in the stream is processed. ToList, toSet, and toMap are the more common uses.

@Test public void streamTest7() { List<Person> personList = new ArrayList<Person>(); Personlist. add(new Person(" Naruto ", 8900, 18, "1", "helix ")); PersonList. Add (new Person(" sasaki ", 8800, 18, "1", "sasaki ")); Personlist. add(new Person(" Sakura ", 7800, 17, "2", "healing ")); Personlist. add(new Person(" ailiya ", 8200, 30, "1", "psychic ")); Personlist. add(new Person(" personList ", 9500, 31, "1", "personList ")); Personlist. add(new Person(" hand ", 7900, 29, "2", "Bahau ")); personList. Add (new Person(" hand ", 7900, 29, "2"," Bahau ")); List<String> list = personlist.stream ().map(person -> person.getarea ()).collect(module.tolist ()); Println (" toList: "+ list); system.out.println (" toList:" + list); Set<Integer> set = personList.stream().filter(person -> person.getage () > 18).map(Person::getAge).collect(Collectors.toSet()); Println (" toSet: "+ set); system.out. println(" toSet:" + set); // Map<? , Person> map = personList.stream().filter(p -> p.getSalary() > 8000) .collect(Collectors.toMap(Person::getName, p -> p)); Println (" toMap: "+ map); system.out. println(" toMap:" + map); // Map<? , Person> map2 = personList.stream().filter(p -> p.getSalary() > 8000) .collect(Collectors.toMap(Person::getName, Function.identity())); Println (" toMap: "+ map2); system.out. println(" toMap:" + map2); }Copy the code

Running result:

conclusion

Thanks for reading. If you have any questions or suggestions, please feel free to leave your own thoughts in the comments section