Use of Lambda expression in Java8 and detailed explanation of Stream API

  • 2021-07-26 07:46:04
  • OfStack

Preface

New features of Java8: Lambda expression, powerful Stream API, new time and date API, ConcurrentHashMap, MetaSpace. Overall, the new features of Java8 make Java run faster, have less code, facilitate parallelism, and minimize null pointer exceptions.

0x00. Pre-data


private List<People> peoples = null;

@BeforeEach void before () {
  peoples = new ArrayList<>();
  peoples.add(new People("K.O1", 21, new Date()));
  peoples.add(new People("K.O3", 23, new Date()));
  peoples.add(new People("K.O4", 24, new Date()));
  peoples.add(new People("K.O5", 25, new Date()));
  peoples.add(new People("K.O2", 22, new Date()));
  peoples.add(new People("K.O6", 26, new Date()));
}

0x01. Extract 1 column from object


/**
*  Extraction 1 Column 
*/
@Test void whenExtractColumnSuccess () {
  // No. 1 1 Kinds of writing 
  List<Integer> ages1 = peoples.stream().map(people -> people.getAge()).collect(Collectors.toList());
  System.out.println("###println: args1----");
  ages1.forEach(System.out::println);

  // Simple 1 Writing of dots 
  List<Integer> ages2 = peoples.stream().map(People::getAge).collect(Collectors.toList());
  System.out.println("###println: args2----");
  ages1.forEach(System.out::println);
}

###println: args1----
21
22
23
24
25
26
###println: args2----
21
22
23
24
25
26


/**
  *  As long as you are older than 25 A man of ten years old 
  */
@Test void whenFilterAgeGT25Success () {
  List<People> peoples1 = peoples.stream().filter(x -> x.getAge() > 25).collect(Collectors.toList());
  peoples1.forEach(x -> System.out.println(x.toString()));
}

People{name='K.O6', age=26, birthday=Wed May 15 22:20:22 CST 2019}

0x03. Numeric column data summation of objects in list


/**
  *  Summation of all ages 
  */
@Test void sumAllPeopleAgeSuccess () {
  Integer sum1 = peoples.stream().collect(Collectors.summingInt(People::getAge));
  System.out.println("###sum1: " + sum1);
  Integer sum2 = peoples.stream().mapToInt(People::getAge).sum();
  System.out.println("###sum2: " + sum2);
}

###sum1: 141
###sum2: 141

0x04. Fetches the first eligible element of the collection


/**
  *  Take out the age is 25 A man of ten years old 
  */
@Test void extractAgeEQ25Success () {
  Optional<People> optionalPeople = peoples.stream().filter(x -> x.getAge() == 25).findFirst();
  if (optionalPeople.isPresent()) System.out.println("###name1: " + optionalPeople.get().getName());

  // Abbreviation 
  peoples.stream().filter(x -> x.getAge() == 25).findFirst().ifPresent(x -> System.out.println("###name2: " + x.getName()));
}

###name1: K.O5
###name2: K.O5

0x05. Regular splicing of object character columns in the collection


/**
  *  Comma splice all names 
  */
@Test void printAllNameSuccess () {
  String names = peoples.stream().map(People::getName).collect(Collectors.joining(","));
  System.out.println(names);
}

K.O1,K.O2,K.O3,K.O4,K.O5,K.O6

0x06. Extract collection elements and convert them to Map


/**
  *  Converts a collection to (name, age)  Adj. map
  */
@Test void list2MapSuccess () {
  Map<String, Integer> map1 = peoples.stream().collect(Collectors.toMap(People::getName, People::getAge));
  map1.forEach((k, v) -> System.out.println(k + ":" + v));

  System.out.println("--------");

  //(name object)
  Map<String, People> map2 = peoples.stream().collect(Collectors.toMap(People::getName, People::getThis));
  map2.forEach((k, v) -> System.out.println(k + ":" + v.toString()));
}

//People Self-implemented method in 
public People getThis () {
  return this;
}

K.O2:22
K.O3:23
K.O1:21
K.O6:26
K.O4:24
K.O5:25
--------
K.O2:People{name='K.O2', age=22, birthday=Wed May 15 22:42:39 CST 2019}
K.O3:People{name='K.O3', age=23, birthday=Wed May 15 22:42:39 CST 2019}
K.O1:People{name='K.O1', age=21, birthday=Wed May 15 22:42:39 CST 2019}
K.O6:People{name='K.O6', age=26, birthday=Wed May 15 22:42:39 CST 2019}
K.O4:People{name='K.O4', age=24, birthday=Wed May 15 22:42:39 CST 2019}
K.O5:People{name='K.O5', age=25, birthday=Wed May 15 22:42:39 CST 2019}

0x07. Grouping by one of the 1 attributes of the collection


/**
  *  Group by name 
  */
@Test void listGroupByNameSuccess() {
  // Add 1 Elements are convenient to see the effect 
  peoples.add(new People("K.O1", 29, new Date()));
  Map<String, List<People>> map = peoples.stream().collect(Collectors.groupingBy(People::getName));

  map.forEach((k, v) -> System.out.println(k + ":" + v.size()));
}

K.O2:1
K.O3:1
K.O1:2
K.O6:1
K.O4:1
K.O5:1

0x08. Average the number of numeric columns of collection objects


/**
  *  Average age of asking for help 
  */
@Test void averagingAgeSuccess () {
  Double avgAge = peoples.stream().collect(Collectors.averagingInt(People::getAge));
  System.out.println(avgAge);
}

23.5

0x09. Sort collections by one of the 1 columns


/**
  *  Sort by age 
  */
@Test void sortByAgeSuccess () {
  System.out.println("### Before sorting ---");
  peoples.forEach(x -> System.out.println(x.getAge()));

  peoples.sort((x, y) -> {
    if (x.getAge() > y.getAge()) {
      return 1;
    } else if (x.getAge() == y.getAge()) {
      return 0;
    }
    return -1;
  });

  System.out.println("### After sorting ---");
  peoples.forEach(x -> System.out.println(x.getAge()));
}

# # # Before sorting--
21
23
24
25
22
26
# # # After sorting--
21
22
23
24
25
26

To be continued

< Source address: https://github.com/cos2a/learning-repo/tree/master/core-java8 >

Summarize


Related articles: