“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

I can’t go back to the for loop when I’m using lambda, and it’s not really good for reading, but it’s actually pretty readable when I’m writing, and here are some of the ways I use it, because we’re wrapping all of our data into maps, so we’re doing lambda with map sets, We can create a List<Map<String, Object>> cusMap to receive the Map,

A: sorting

  1. ForEach is used when we want to iterate over the value of a key in the set

    cusMap.stream().forEach(o -> System.out.println(o.get("aaa").toString()));
    Copy the code

2. We do this when we want to sort them by a given key (referring to sorted). We do this in ascending order, and ** if we want to sort the second field we add.thencomparing () to the Comparator.comparing, The internal parameters are the same as the parameters in Comparing ()

List<Map<String, Object>> aaa = cusMap.stream()
                                .sorted(Comparator.comparing(e -> Double.valueOf(e.get("aaa").toString())))
                                .collect(Collectors.toList());
Copy the code

3. When we want to sort by ** key ** we do so by comparator.reverseOrder () on the comparator.paring feature.

List<Map<String, Object>> aaa = cusMap.stream()
                                .sorted(Comparator.comparing(e -> Double.valueOf(e.get("aaa").toString()),Comparator.reverseOrder()))
                                .collect(Collectors.toList());
Copy the code

Filter 2:

4. When we want to filter data by a key, we can use filter to process the data

cusMap.stream().filter(o -> Double.valueOf(o.get("aaa").toString())>2).collect(Collectors.toList());
Copy the code

5. Filter can also be used to determine whether the value is equal to or not equal to a certain value for filtering

cusMap.stream().filter(o -> "2".equals(o.get("aaa").toString())).collect(Collectors.toList());
Copy the code

6. Sometimes we might want to return the list instead of the list. Instead, we want to return the value of a key as the key of Map

> AAA1, In this case, you can use Collectors. ToMap
,>

aaa.stream().collect(Collectors.toMap(k -> k.get("aaa").toString(), Function.identity(), (key1, key2) -> key2))
Copy the code

And then get that key to get all the maps

7. If you want anymatch to return true or FALSE, you can use anymatch

boolean flag = cusMap.stream().anyMatch(o -> o.get("aaa").toString().equals("3"));
Copy the code

Returns true as long as there are any matches; If it is multiple judgment, can add a && in anymatch or | | can;

If there are any more, please add them, and I’ll add some common methods, okay