List.stream().map() usage in Java8

1. The usage of stream.map() in Java8
Introduction
This is the newly added functional programming method in java 8. A simple understanding of functional programming is to pass methods as parameters, which can improve writing efficiency and reduce code redundancy.

example

class Test{
    
    
  public static void main(String[] args) {
    
    
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);  
       /*使用函数式编程*/
       /* 第一种方式*/ 
        List<Integer> listAdd = list.stream().map(s -> s + 2).collect(Collectors.toList());
        System.out.println("listAdd" + listAdd);
        /* 第二种方式*/
        List<Integer> listAdd02 = list.stream().map(Test::add2).collect(Collectors.toList());
        System.out.println("listAdd02" + listAdd02);     
  }
  
  /*声明一个方法,加2,并返回结果*/
  private static int add2(Integer temp){
    
    
        return  temp + 2;
    }
}

2. We can see that in the method of code list.stream().map(s -> s + 2), s is each element in the list list, which is equivalent to traversing the elements of the list list, and we get the list list Add 2 to the number of elements, and add 2 to each element in the list.
3. The annotation
strem() is to convert the data in the list into a stream form, and then pass each value in each list to the map Go to the method in and build a new list through collect(Collectors.toList()). The final printed result is:

listAdd[3, 4, 5]
listAdd02[3, 4, 5]

Guess you like

Origin blog.csdn.net/qq_36570506/article/details/131323185