sequence

Since the introduction of streams in Java8, it has been common to see someone else writing elegant and concise code in a code review and forget or not know when to use stream style to modify code. This article also summarizes and expands some usages, on the one hand for my own review, on the other hand to share with readers.

What is the flow

A stream is a sequence of elements that does not store elements or modify the original source.

Stream provides a high-level abstraction of Java collection operations and expressions in an intuitive manner similar to querying data from a database with SQL statements, allowing programmers to write efficient, clean, and concise code.

The flow of elements in the pipe is processed through intermediate operations, and the final operation yields the result of the previous processing.

How to create a flow

Stream.of(T… Values) and the Stream of (T, T)

Stream.of("Zhang"."Bill"."Fifty")
Copy the code

Stream.iterate(T seed, UnaryOperator f)

// An infinite stream is changed to a finite stream by adding the limit operation
Stream.iterate(0, n -> n + 1).limit(10)
Copy the code

Stream.generate(Supplier s)

Stream.generate(Math::random).limit(10)
Copy the code

Arrays.stream(T[] array)

// String[] names = {" name "," name "," name "};
Arrays.stream(names)
Copy the code

Collection.stream()

/ / a List < String > names = Arrays. The asList (" zhang ", "bill", "detective");
names.stream()
Copy the code

What can be done with flow

sum

// List<Integer> numberList = Arrays.asList(1,2,3);
int sum = numberList.stream().reduce((x,y) -> x + y).orElse(0);
Copy the code

Filter data

// List
      
        alphaList = Arrays.asList("a","ab","abc","acb");
      

alphaList.stream().filter(e -> e.contain("a")).collect(toList())
Copy the code

Concatenated string

// String[] names = {" name "," name "," name "};

/ / method
names.reduce("",String::concat)

/ / method 2
names.collect(() -> new StringBuilder(),
        (sb, str) -> sb.append(str),
        (sb1,sb2) -> sb1.append(sb2))
    .toString();
    
/ / method 3
names.collect(Collectors.joining());
Copy the code

Turn the POJO collection into a map

/** public class User { private Long id; private String name; // omit getters, setters, constructors, etc.} */

// Build a mapping between attributes
Map<Long,String> idNameMap = users.stream().collect(Collectors.toMap(User::getId,User::getName));

// Build a mapping between attributes and instances
Map<Long,User> userMap = users.stream().collect(Collectors.toMap(User::getId, u -> u));
// or userMap = users.stream().collect(Collectors. ToMap (User::getId, function.identity ()));
Copy the code

Group POJO collections

/** public class User { private Long id; private String name; private Integer age; private Boolean isLeader; // omit getters, setters, constructors, etc.} */

// Divide users into leader and Employee
Map<Boolean,List<User>> isLeaderMap = users.stream().collect(Collectors.partitioningBy(User::getIsLeader));

// Group users by age
Map<Integer,List<User>> ageMap = users.stream().collect(Collectors.groupingBy(User::getAge));
Copy the code

Sort the data

// List
      
        alphaList = Arrays.asList("a","ab","abc","acb");
      

// Sort by length
alphaList.stream().sorted((s1,s2) -> s1.length() - s2.length()).collect(toList());
alphaList.stream().sorted(Comparator.comparingInt(String::length)).collect(toList());

// Sort by length first, alphabetically if the length is the same
alphaList.stream().sorted(comparing(String::length).thenComparing(naturalOrder())).collect(toList());
Copy the code

Determines whether data that conforms to a certain rule exists in the collection

// List
      
        alphaList = Arrays.asList("a","ab","abc","acb");
      

// Whether a string containing the letter a exists
alphaList.stream().anyMatch(e -> e.contains("a"));

// Whether all strings contain the letter A
alphaList.stream().allMatch(e -> e.contains("a"));

// Whether all strings do not contain the letter A
alphaList.stream().noneMatch(e -> e.contains("a"));
Copy the code

other

Of course there are many more things that can be done, but the ones the author uses most are listed and others that are too simple or not commonly used are omitted.

If you find this article helpful, please like it and share it with us. If you are interested, you can also browse the author’s other articles. If you think this article is a waste of your time, please leave your comments in the comments section. If you have any questions, please leave a message. The author is willing to spend time and energy to find answers and discuss them together.