preface

The following are my notes on lambda collation, which are still being improved. If you have a better writing method, welcome to put forward below

Code comments I wrote very clearly read the comments

1. The id and name of the List storage object are converted into a Map collection
 // Create a collection to store user objects
        List<UserInfo> userInfoList = new ArrayList<>();
        UserInfo user = new UserInfo();
        user.setUserId(1L);
        user.setRealName("Zhang");
        userInfoList.add(user);
        Map<Long, String> map = 
                  // Create a parallel stream
                  userInfoList.parallelStream()
                  // Add filter criteria.filter(u -> u ! =null)
                  // Return a Map set. Key is userId and value is user name
                .collect(toMap(UserInfo::getUserId, UserInfo::getRealName));
        // Iterate over the print
         map.forEach((k,v)->{
             System.out.println("key:"+k+""+"value: "+v);
         });
Copy the code
2.List Indicates the filter traversal of the storage object
  // Create a collection to store user objects
        List<UserInfo> userInfoList = new ArrayList<>();
        UserInfo user = new UserInfo();
        user.setUserId(1L);
        user.setRealName("zs");
        userInfoList.add(user);
        UserInfo user2 = new UserInfo();
        user2.setUserId(2L);
        user2.setRealName("ls");
        userInfoList.add(user2);
        // Check whether the set is empty
        Optional.ofNullable(userInfoList)
                // Return the default if the collection is empty
                .orElseGet(ArrayList::new)
                // Creating parallel streams is equivalent to multi-threaded disorder
                .parallelStream()
                // The filter name cannot be empty
                .filter(u -> StringUtils.isNotBlank(u.getRealName()))
                // Convert to list
                .collect(Collectors.toList())
                / / traverse
                .forEach(u->{
                    System.out.println(u.getRealName());
                });
Copy the code
3.List stores string data in case
List<String> strList = Arrays.asList("a"."b"."d"."s"."n"."a"."s"."c"."d".null);
        // Create a parallel stream
        strList.parallelStream()
                // Filter non-null judgment
                .filter(s-> StringUtils.isNotBlank(s))
                // uppercase to toLowerCase toLowerCase
                .map(String::toUpperCase)
                / / traverse
                .forEach(System.out::println);
Copy the code
4. Get the List data and get a comma-separated string
List<String> strList = Arrays.asList("a"."b"."d"."s"."n"."a"."s"."c"."d"."b"."");
        String str = strList.parallelStream()
                // Filter conditions
                .filter(s -> StringUtils.isNotBlank(s))
                // Separate data with commas
                .collect(Collectors.joining(","));
        / / print
        System.out.println(str);
Copy the code
5. The List to heavy
List<String> strList = Arrays.asList("a"."b"."d"."s"."n"."a"."s"."c"."d"."b");
// The original set length
System.out.println(strList.size());
// Return a new LIS with the repeated elements removed
List<String> noRepeatList = strList.stream()
/ / to heavy
.distinct()
// Convert to a new collection
.collect(Collectors.toList());
// New set length
System.out.println(noRepeatList.size());
Copy the code
6.List stores the maximum value and minimum value of searching for int data
       // create a set to store int data
        List<Integer> ints = Stream.of(1.2.4.3.5).collect(Collectors.toList());
        // Create a parallel stream
        int asInt = ints.parallelStream()
                // Find the maximum value
                .max(comparing(i->i))
                // Return the maximum value
                .get();
        / / print
        System.out.println(asInt);

       // create a set to store int data
        List<Integer> ints2 = Stream.of(1.2.4.3.5).collect(Collectors.toList());
        // Create a parallel stream
        int asInt = ints2.parallelStream()
                // Find the minimum value
                .min(comparing(i->i))
                // Return the minimum value
                .get();
 		// The maximum length in the set
        List<String> strList = Arrays.asList("a"."b"."d"."s"."n"."yu"."luo"."shuai"."spot"."xhuai");
        int max = strList.stream()
                // Determine the length
                .mapToInt(s -> s.length())
                // Get the maximum value of the judgment condition
                .max()
                // Convert to int length
                .getAsInt();
        // Print the maximum length
        System.out.println(max);
                strList.stream()
                // Filter criteria find the maximum value in the element
                .filter(s -> s.length() == max)
                 // Convert to list
                .collect(Collectors.toList())
                 // Iterate over the print
                .forEach(s->{
                    System.out.println(s);
                });

        // The minimum length in the set
        List<String> strList2 = Arrays.asList("a"."b"."d"."s"."nd"."yu"."luo"."shuai");
        // Create a sequential stream
        int min = strList2.stream()
                // Determine the length
                .mapToInt(s -> s.length())
                // Get the minimum length
                .min().getAsInt();
        // Print the minimum length
        System.out.println(min);
Copy the code
7. The List collection takes the square of the int element
 List<Integer> list = Arrays.asList(1.2.6.9);
        // Create a serial stream
        list.stream()
                // Square each element
                .map(s -> s * s).collect(Collectors.toList())
                / / print
                .forEach(System.out::println);
Copy the code
8.List returns a specific result
		// Returns a specific result
        List<String> strList = Arrays.asList("a"."b"."c"."d"."e"."f");
        // Create a serial stream
        strList.stream()
                .skip(2) // Discard the first two elements
                .limit(3) // Return the first three elements
                // Convert to set
                .collect(Collectors.toList())
                / / print
                .forEach(System.out::println);
Copy the code
9.List sorts data of type int
   List<Integer> ints = Arrays.asList(5.8.9.4.3.2.7.1.6.2);
        // Create a sequential stream
        ints.stream()
                // Sort in reverse order
                // Sort from front to back
                .sorted((ln1, ln2) -> (ln1 - ln2)) / / sorting
                .distinct()// Remove duplicate elements optional Do not use this method to duplicate elements
                // Convert to set
                .collect(Collectors.toList())
                / / traverse
                .forEach(System.out::println);
Copy the code
10.List matching rule
       /** * allMatch: returns true for all elements of the Stream that match the passed predicate * anyMatch: Returns true for all elements of the Stream that match the passed predicate * noneMatch: None of the elements in Stream match the passed predicate, which returns true */
        List<String> strList = Arrays.asList("a"."b"."d"."s"."n"."a"."s"."c"."d"."b");
        // Check whether there are c elements in the set. Return Boolean
        boolean isExits = strList.stream().anyMatch(s -> s.equals("c"));
        / / print true
        System.out.println(isExits);
        List<String> strList2 = Arrays.asList("a"."b"."d"."s"."n"."a"."s"."c"."d"."");
        // Check whether the set is not empty
        boolean isFull = strList2.stream().allMatch(s -> s.isEmpty());
        / / print false
        System.out.println(isFull);
        // None of the elements in Stream match the passed predicate, which returns true
        boolean isNotEmpty = strList2.stream().noneMatch(s -> s.isEmpty());
        / / print false
        System.out.println(isNotEmpty);
Copy the code
11.List Stores object data into groups based on conditions
       // Create a collection to store user objects
        List<UserInfo> userInfoList = new ArrayList<>();
        UserInfo user = new UserInfo();
        user.setUserId(5L);
        user.setRealName("zs");
        userInfoList.add(user);
        UserInfo user2 = new UserInfo();
        user2.setUserId(3L);
        user2.setRealName("ls");
        userInfoList.add(user2);
        // Return a map
        Map<Long, List<UserInfo>> map = userInfoList.parallelStream()
                // The filter condition name cannot be empty
                .filter(s -> StringUtils.isNotBlank(s.getRealName()))
                // Group with userId
                .collect(groupingBy(UserInfo::getUserId));
            // Iterate over the print
            map.forEach((k,v)->{
                System.out.println("key:"+k+""+"value:"+v);
            });
Copy the code
12. Reductive usage in streams
 		// Create a collection to store user objects
        List<UserInfo> userInfoList = new ArrayList<>();
        UserInfo user = new UserInfo();
        user.setUserId(5L);
        user.setRealName("zs");
        userInfoList.add(user);
        UserInfo user2 = new UserInfo();
        user2.setUserId(3L);
        user2.setRealName("ls");
        userInfoList.add(user2);
        // Sum by reduction
        Optional<Long> reduce = userInfoList.stream()
                / / filter
                .filter(u -> StringUtils.isNotBlank(u.getRealName()))
                // Extract the ID of userInfo
                .map(UserInfo::getUserId)
                // Sum by reduction
                .reduce(Long::sum);
        System.out.println(reduce.get());
        // reduce to the maximum value
        Optional<Long> reduce1 = userInfoList.stream()
                / / extraction
                .map(UserInfo::getUserId)
                // Find the maximum value
                .reduce(Long::max);
        System.out.println(reduce1.get());
        // reduce to the minimum
        Optional<Long> reduce2 = userInfoList.stream()
                / / extraction
                .map(UserInfo::getUserId)
                // Find the minimum value
                .reduce(Long::min);
        System.out.println(reduce2.get());
        // Find the average value
        OptionalDouble average = userInfoList.stream()
                / / extraction
                .mapToLong(UserInfo::getUserId)
                // Find the average value
                .average();
        System.out.println(average.getAsDouble());
  		/ / count
        long count = userInfoList.stream()
                / / extraction
                .mapToLong(UserInfo::getUserId)
                / / count
                .count();
        / / print
        System.out.println(count);
Copy the code
Java8 summaryStatijstics is used together with the device
 
// Create a collection to store user objects
        List<UserInfo> userInfoList = new ArrayList<>();
        UserInfo user = new UserInfo();
        user.setUserId(5L);
        user.setRealName("zs");
        userInfoList.add(user);
        UserInfo user2 = new UserInfo();
        user2.setUserId(3L);
        user2.setRealName("ls");
        userInfoList.add(user2);
					/ / summaryStatijstics use
LongSummaryStatistics summaryStatistics = userInfoList.stream()
    			/ / extraction
                .mapToLong(UserInfo::getUserId)
                .summaryStatistics();
        // Find the maximum value
        System.out.println("Maximum value:"+summaryStatistics.getMax());
        // Find the minimum value
        System.out.println("Minimum:"+summaryStatistics.getMin());
        / / sum
        System.out.println("Sum for:"+summaryStatistics.getSum());
        / / count
        System.out.println("Count:"+summaryStatistics.getCount());
 		// Find the average value
        System.out.println("Average:"+summaryStatistics.getAverage());
Copy the code
14.Java8 String conversion
		// String to character array
        List<String> strList = Arrays.asList("a"."b"."d"."s"."n"."yu"."luo"."shuai"."spot"."xhuai");
       // Create a collection to hold the character element
        List<Character> newList = new ArrayList<>();
                        // Convert to char array stream
        strList.stream().map(String::toCharArray)
                // Iterate over the character element
                .forEach(s->{
                    // Iterate over each element
                    for (char c : s) {
                        / / storenewList.add(c); }});/ / print
        newList.stream().forEach(System.out::println);
	 // The second way
	 strList.stream().map(String::toCharArray)
                // Integrate the converted char[] array
                .flatMapToInt(chars -> CharBuffer.wrap(chars).chars())
                // Convert to char
                .mapToObj(e -> (char) e)
                // Convert to collection storage
                .collect(Collectors.toList())
                / / traverse
                .forEach(System.out::println);
Copy the code
Return a new collection of objects from the List
       // Construct test data
        List<Student> list = new ArrayList<>();
        Student stu = new Student();
        stu.setId(1L);
        stu.setName("ZS");
        list.add(stu);
        Student stu2 = new Student();
        stu2.setId(2L);
        stu2.setName("ls");
        list.add(stu2);
        list.add(null);
        System.out.println(list);
         List<Person> perList = list.stream()
                    // Filter conditions
                    .filter(Objects::nonNull)
                    // Construct information
                    .map(s -> {
                        Person person = new Person();
                        // reassign
                        person.setId(s.getId());
                        person.setAge(18);
                        person.setName(s.getName());
                        return person;
                    })
                    // return the new collection
                    .collect(Collectors.toList());
            / / print
            perList.forEach(System.out::println);
Copy the code
16. Turn the object into a stream and operate on it
       // Construct test data
        UserInfoVO postUserInfo = new UserInfoVO();
        postUserInfo.setUserId(143L);
        postUserInfo.setCreateUserId(153L);
        postUserInfo.setMobile("12345678910");
        // Construct the argument to return
        OrderMessageRequest newOrderMessageRequest = Stream.of(postUserInfo)
                    .map(u -> {
                        // Filter conditions
                        if((! u.getCreateUserId().equals(u.getUserId())) && StringUtils.isNotBlank(u.getMobile())) {// Construct the data needed to send SMS
                            OrderMessageRequest orderMessageRequest = new OrderMessageRequest();
                            // Get the mobile phone number of the Courier
                            orderMessageRequest.setMobile(u.getMobile());
                            // I am a Courier
                            orderMessageRequest.setIsCourierStation("1");
                            System.out.println("Dak reassigned successfully");
                            return orderMessageRequest;
                        } 
                            // It's not a station person texting an operations person
                            OrderMessageRequest orderMessageRequest =  new OrderMessageRequest();
                            // Not a stagecoach
                            orderMessageRequest.setIsCourierStation("0");
                            System.out.println("Operation reassignment successful");
                            return orderMessageRequest;
                    })
                 	There is only one element here because we only have one object
                    .findAny()
                    // Returns the default if empty
                    .orElseGet(OrderMessageRequest::new);  
Copy the code
17. Extract a column from list into a new collection
 List<UserLoginInfoVO> list = new ArrayList<>();
        UserLoginInfoVO userLoginInfoVO = new UserLoginInfoVO();
        userLoginInfoVO.setMobile("15655654654");
        userLoginInfoVO.setPushToken("textPushToken");
        list.add(userLoginInfoVO);
        UserLoginInfoVO userLoginInfoVO2 = new UserLoginInfoVO();
        userLoginInfoVO2.setMobile("12345678910");
        userLoginInfoVO2.setPushToken("textPushToken2");
        list.add(userLoginInfoVO2);
        UserLoginInfoVO userLoginInfoVO3 = new UserLoginInfoVO();
        userLoginInfoVO3.setMobile("123565645567");
        userLoginInfoVO3.setPushToken("textPushToken3");
        list.add(userLoginInfoVO3);
        list.stream()
                / / filter.filter(u -> u ! =null)
                / / extraction
                .map(UserLoginInfoVO::getMobile)
                // Convert to a new collection
                .collect(Collectors.toList())
                / / print
                .forEach(System.out::println);
Copy the code
18. Extract data from list into array
List<UserLoginInfoVO> list = new ArrayList<>();
        UserLoginInfoVO userLoginInfoVO = new UserLoginInfoVO();
        userLoginInfoVO.setMobile("15655654654");
        userLoginInfoVO.setPushToken("textPushToken");
        list.add(userLoginInfoVO);
        UserLoginInfoVO userLoginInfoVO2 = new UserLoginInfoVO();
        userLoginInfoVO2.setMobile("12345678910");
        userLoginInfoVO2.setPushToken("textPushToken2");
        list.add(userLoginInfoVO2);
        UserLoginInfoVO userLoginInfoVO3 = new UserLoginInfoVO();
        userLoginInfoVO3.setMobile("123565645567");
        userLoginInfoVO3.setPushToken("textPushToken3");
        list.add(userLoginInfoVO3);
        String[] arrays = list.stream()
                / / extraction
                .map(UserLoginInfoVO::getMobile)
                // Convert to a string array
                .toArray(String[]::new);
        / / print
        Stream.of(arrays).forEach(System.out::println);
Copy the code
Group by a certain condition
// Group by a condition
// Assign a group of ages to adults and minors
List<Integer> ageList = Arrays.asList(11.22.13.14.25.26);
    Map<Boolean, List<Integer>> ageMap = ageList.stream()
            .collect(Collectors.partitioningBy(age -> age > 18));
    System.out.println("Minor:" + ageMap.get(false));
    System.out.println("Adulthood:" + ageMap.get(true));
 // Output the result
 // Minor: [11, 13, 14]
 // Adult: [22, 25, 26]
Copy the code