This article has participated in the weekend study program, click on the link for details: activities link

preface

An important use of Java Lambda expressions is to simplify some anonymous inner classes. This is a syntax-candy in Java 8, which allows functions to be passed as arguments to a method. Using Lambda expressions not only makes code more compact, but also reduces the amount of code. It doesn’t smell too good. This article is a summary of documentation and learning, not the underlying principles, just the usage level.

New methods supported by the collection

  • Collection: forEach(), stream(), removeIf(), spliterator(), parallelStream()
  • List: sort(), replaceAll()
  • The Map: ForEach (), getOrDefault(), replaceAll(), putIfAbsent(), remove(), replace(), computeIfAbsent(), compute(), merge()

Sort the List

Create a Test object, then add the object to the List, and then use Lambda sort as follows:

public static class Test { private String name; public Test(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static void main(String[] args) { List<Test> list = new ArrayList<>(); list.add(new Test("lch")); list.add(new Test("abc")); list.add(new Test("xyz")); System.out.println(" sort list: "+ json.tojson (list).toString()); (p1, p2) -> p1.getName().compareto (p2.getName()) Collections.sort(list, (p1, p2) -> p1.getName().compareto (p2.getName())); Collections.sort(list, Comparator.comparing(Test::getName)); System.out.println(" sorted list: "+ json.tojson (list).toString()); }Copy the code

Running results:

Before ordering list: [{" name ":" LCH "}, {" name ":" ABC "}, {" name ":" xyz "}] sorted list: [{" name ":" ABC "}, {" name ":" LCH "}, {" name ":" xyz "}]Copy the code

The List cycle

Requirements: Loop through the List and find the records that meet the criteria and save them to the new List output.

List<String> list = new ArrayList<>(); list.add("lch"); list.add("abc"); list.add("xyz"); List<String> list1 = new ArrayList<>(); list.forEach(e -> { if (e.equals("lch")) { list1.add(e); }}); System.out.println(" print only list of specified characters: "+ json.tojson (list1).toString());Copy the code

Running results:

Print only list of specified characters: [" LCH "]Copy the code

List’s removeIf() method

Requirement: Once again, the loop now requires that the deleted value be the remaining value of the LCH.

List<String> list = new ArrayList<>(); list.add("lch"); list.add("abc"); list.add("xyz"); RemoveIf (e -> e.quals (" LCH ")); System.out.println(" list: "+ json.tojson (list).tostring ());Copy the code

Running results:

Delete LCH from list: [" ABC ","xyz"]Copy the code

The List of the replaceAll ()

Requirement: Convert all records of length greater than 2 to uppercase.

List<String> list = new ArrayList<>(); list.add("lch"); list.add("abc"); list.add("xyz"); list.add("a"); list.add("it"); ReplaceAll (e -> {if (e.length() > 2) {return e.toupperCase (); } return e; }); System.out.println(" length greater than 2 to uppercase value after list: "+ json.tojson (list).tostring ());Copy the code

Running results:

List with length greater than 2 after capitalized value: ["LCH","ABC","XYZ","a","it"]Copy the code

The Map of circulation

Requirement: Circularly print map

Map<String, String> map = new HashMap<>(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three"); ForEach ((k,v)-> system.out.println (" k="+k+",value: "+v));Copy the code

Running results:

Loop output k=1 and value is: one. Loop output k=2 and value is: two. Loop output k=3 and value is: threeCopy the code

The map of getOrDefault ()

Requirement: Take the value of valus corresponding to key in the map. If no value exists, return the default value.

Map<String, String> map = new HashMap<>(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three"); Println (" + map.getorDefault ("3", "zero")) + map.getordefault ("3", "zero"); System.out.println(" + map.getorDefault ("4", "zero"));Copy the code

Running results:

Take the value of map key 3 and return the following value: three Take the value of map key 4 and return the following value: zeroCopy the code

Map putIfAbsent(), replaceAll(), merge(),compute() methods

Requirements: See the code directly

Map<String, String> map = new HashMap<>(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three"); Map. putIfAbsent("3", "III"); map.putIfAbsent("5", "five"); System.out.println(" putIfAbsent value: "+ json.tojsonString (map)); // loop to uppercase map.replaceAll((k, v) -> v.toupperCase ()); System.out.println("map loop to uppercase value: "+ json.tojsonString (map)); // merge map.merge("3", "OOO", (v1, v2) -> v1+v2); Println ("map merge value: "+ json.tojsonString (map)); Map.pute ("10", (k,v) -> v==null? "ten" : v.cat ("ten")); map.compute("1", (k,v) -> v==null ? "one" : v.concat("III")); System.out.println(" compute for map: "+ json.tojsonString (map));Copy the code

The results

Map performed putIfAbsent value: {" 1 ":" one ", "2", "two", "3", "three", "5" : "five"} turn map circulation capital value: {" 1 ", "ONE", "2", "TWO", "3", "THREE", "5" : "FIVE"} map splicing merge value: {" 1 ":" ONE ", "2", "TWO", "3" : "THREE OOO", "5" : "FIVE"} map of compute value: {"1":"ONEIII","2":"TWO","3":"THREE OOO","5":"FIVE","10":"ten"}Copy the code

Map’s computeIfAbsent() method

Requirement: Implement a multi-valued Map, the definition of Map may be Map<K,Set>, need to put values into the Map, not the pre-lambda code to write this.

Map<Integer, Set<String>> map = new HashMap<>(); If (map.containskey (1)) {// Update map.get(9).add(" LCH "); } else {// Set<String> valueSet = new HashSet<>(); valueSet.add("lch"); map.put(9, valueSet); } system.out.println (" + json.tojson (map).tostring ()); // equivalent to Map<Integer, Set<String>> map1 = new HashMap<>(); map1.computeIfAbsent(9, v -> new HashSet<>()).add("lch"); System.out.println(" Map computeIfAbsent value: "+ json.tojson (map1).toString());Copy the code

Running results:

{"9":[" LCH "]} Map computeIfAbsent: {"9":[" LCH "]}Copy the code

conclusion

Lambda expressions support lists and maps. Next time, we will focus on stream, which is the main character of Java functional programming. Good night!