This is the 5th day of my participation in the August More Text Challenge

preface

Streaming programming for higher-order functions such as Map, Reduce, and filter can be found in many languages. The corresponding function in Java is the Stream operation. A similar code would look like this:

// Generate 1357 and print
Arrays.stream(new int[] {1.3.5.7}).forEach(System.out::println);
Copy the code

So today I’m going to clean up a bit about Java Stream streaming programming.

On Stream

  • Stream is a new abstraction added to Java8 called a Stream that lets you process data in a declarative way.
  • Stream can greatly increase the productivity of Java programmers, allowing programmers to write efficient, clean, and concise code.
  • The operation of a Stream is strung together as a pipe. A pipe starts with a data source, contains several intermediate operations, and ends with an endpoint operation.

Simple to use

Here is a simple introduction to use in Java:

Map Filter Reduce

List<Integer> list = List.of(1.2.3.4.5.6.7.8.9);

/ / sum
// Integer sumResult = list.stream().reduce(0, (a, b) -> a + b);
Integer sumResult = list.stream().reduce(0, Integer::sum);
/ / 45
System.out.println(sumResult);

// go through the number group
list.forEach(System.out::print);
/ / 123456789
System.out.println();

// Returns the square of the array element
List<Integer> numbersList = list.stream().map(i -> i * i).collect(Collectors.toList());

// [1, 4, 9, 16, 25, 36, 49, 64, 81]
System.out.println(numbersList);


List<Integer> evenNumbersList = list.stream().filter(i -> i % 2= =0).collect(Collectors.toList());
// Filter out even numbers in array [2, 4, 6, 8]
System.out.println(evenNumbersList);

// Filter out the odd number in the array and return the square of the element
List<Integer> numbers = list.stream().filter(i -> i % 2! =0).map(i -> i * i).collect(Collectors.toList());
System.out.println(numbers);
Copy the code

Collector

Typically used at the end of a stream operation, for definition of a return value on a result set or for advanced operations. Common operations are used to return specific collections:

  • Collectors.toList()
  • Collectors.toMap()
  • Collectors.toSet()
  • Collectors.toCollection()
  • Collectors.toConcurrentMap()

Common demos are listed below:

List<String> language = List.of("Java"."Python"."Rust"."Go"."C++"."C"."C#"."JavaScript");


// Convert the array elements to uppercase letters and concatenate them with commas
String collect1 = language.stream().collect(Collectors.collectingAndThen(Collectors.joining(","), String::toUpperCase));
// JAVA,PYTHON,RUST,GO,C++,C,C#,JAVASCRIPT
System.out.println(collect1);

// Implement grouping by array elements
Map<Integer, List<String>> collect2 = language.stream().collect(Collectors.groupingBy(String::length));
// {1=[C], 2=[Go, C#], 3=[C++], 4=[Java, Rust], 6=[Python], 10=[JavaScript]}
System.out.println(collect2);

// The length converted to a string conflicts with the hash map of the string, which overwrites the former
Set<String> collect3 = language.stream().collect(Collectors.toCollection(HashSet::new));
// language.stream().collect(Collectors.toSet());
// [C#, Java, C++, Rust, C, JavaScript, Go, Python]
System.out.println(collect3);


// The length converted to a string conflicts with the hash map of the string, which overwrites the former
Map<Integer, String> collect4 = language.stream().collect(Collectors.toMap(String::length, String::new,(existing, replacement) -> existing));
// {1=C, 2=Go, 3=C++, 4=Java, 6=Python, 10=JavaScript}
System.out.println(collect4);
Copy the code

Use the advanced

In simple use are relatively common and unified understanding of the example. Let’s look at some more complicated examples.

Data preparation

The Person class uses Lombok’s Builder and Data annotations.

@Builder(toBuilder = true)
@Data
class Person {
    private Integer height;
    private Integer age;
    private String name;
    private String city;

}

Person p1 = new Person.PersonBuilder().name("bob").height(150).city("shanghai").age(15).build();
Person p2 = new Person.PersonBuilder().name("andy").height(160).city("beijing").age(18).build();
Person p3 = new Person.PersonBuilder().name("tom").height(170).city("xian").age(19).build();
Person p4 = new Person.PersonBuilder().name("cat").height(180).city("shanghai").age(25).build();


ArrayList<Person> persons = new ArrayList<>();
persons.add(p1);
persons.add(p2);
persons.add(p3);
persons.add(p4);

Copy the code

Instance to explain

The following code implements the following functions:

  1. Sets additional fields to the people array by age
  2. Group the people in the array by city
  3. If there are many people in the group, choose the tallest member

// Requires a Comparator for height
Comparator<Person> byHeight = Comparator.comparing(Person::getHeight);

Map<String, Person> collect = persons.stream().peek(item -> {
    String temp = item.getAge() >= 18 ? "Adult" : "Minor";
    item.setExtra(temp);
}).collect(
        Collectors.groupingBy(
                Person::getCity,
                Collectors.reducing(p1, BinaryOperator.maxBy(byHeight))
        )
);

// {xian=Person(height=170, age=19, name= Tom, city=xian, extra= adult), Shanghai =Person(height=180, age=25, name=cat, City = Shanghai, extra= adult), Beijing =Person(height=160, age=18, name= Andy, city= Beijing, extra= adult)}
System.out.println(collect);
Copy the code