java常用lambda

java常用lambda

十二月 28, 2020

Lambda 详细操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Employee {

private String name;
private int salary;
private String office;
}


public class ExampleEmployee {

private static List<Employee> employeeList = Lists.newArrayList();

static{
employeeList.add(Employee.builder().name("Matt").salary(5000).office("New York").build());
employeeList.add(Employee.builder().name("Steve").salary(6000).office("London").build());
employeeList.add(Employee.builder().name("Carrie").salary(20000).office("New York").build());
employeeList.add(Employee.builder().name("Peter").salary(7000).office("New York").build());
employeeList.add(Employee.builder().name("Pat").salary(8000).office("London").build());
employeeList.add(Employee.builder().name("Tammy").salary(29000).office("Shanghai").build());
}

public static void main(String[] args) {
//anyMatch
boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
System.out.println(isMatch);

//返回所有salary大于6000
boolean matched = employeeList.stream().allMatch(employee -> employee.getSalary()>4000);
System.out.println(matched);

//找出工资最高
Optional<Employee> hightestSalary = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
System.out.println(hightestSalary);

//返回姓名列表
List<String> names = employeeList.stream().map(employee -> employee.getName()).collect(Collectors.toList());
System.out.println(names);

//List转换成Map
Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));

//统计办公室是New York的个数
long officeCount = employeeList.stream().filter(employee -> employee.getOffice().equals("Shanghai")).count();
System.out.println(officeCount);

//List转换为Set
Set<String> officeSet = employeeList.stream().map(employee -> employee.getOffice()).distinct().collect(Collectors.toSet());
System.out.println(officeSet);

//查找办公室地点是New York的员工
Optional<Employee> allMatchedEmployees = employeeList.stream().filter(employee -> employee.getOffice().equals("New York")).findAny();
System.out.println(allMatchedEmployees);

//按照工资的降序来列出员工信息
List<Employee> sortEmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
//按照名字的升序列出员工信息
List<Employee> sortEmployeeByName = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
System.out.println(sortEmployeeList);
System.out.println("按照名字的升序列出员工信息:" + sortEmployeeByName);

//获取工资最高的前2条员工信息
List<Employee> top2EmployeeList= employeeList.stream()
.sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary()))
.limit(2)
.collect(Collectors.toList());
System.out.println(top2EmployeeList);

//获取平均工资
OptionalDouble averageSalary = employeeList.stream().mapToInt(employee->employee.getSalary()).average();
System.out.println("平均工资:" + averageSalary);

//查找New York
OptionalDouble averageSalaryByOffice = employeeList.stream().filter(employee -> employee.getOffice()
.equals("New York"))
.mapToInt(employee->employee.getSalary())
.average();
System.out.println("New York办公室平均工资:" + averageSalaryByOffice);

}
}

java8常用操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
public class EmployeeTest {

public static List<Employee> generateData() {
return Arrays.asList(new Employee("Matt", 5000, "New York"),
new Employee("Steve", 6000, "London"),
new Employee("Carrie", 10000, "New York"),
new Employee("Peter", 7000, "New York"),
new Employee("Alec", 6000, "London"),
new Employee("Sarah", 8000, "London"),
new Employee("Rebecca", 4000, "New York"),
new Employee("Pat", 20000, "New York"),
new Employee("Tammy", 9000, "New York"),
new Employee("Fred", 15000, "Tokyo"));
}

public static Map<String, Integer> generateMapData() {
Map<String, Integer> items = Maps.newHashMap();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);

return items;
}


@Test
public void testEmployee() {
List<Employee> results = generateData();

//打印出名字是Steve的员工信息
results.forEach(c -> {
if (c.getName().equals("Steve")) {
System.out.println(c);
}
});

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

//找出年薪超过6000的员工
results.stream().filter(c -> c.getSalary() >= 60000).forEach(c -> System.out.println(c));

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

//java8遍历map
Map<String, Integer> map_ = generateMapData();
map_.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));

System.out.println("---->>>>分组>>>-----");

//java8 分组操作
Map<String, List<Employee>> groupMap = results.stream().collect(Collectors.groupingBy(c -> c.getOffice()));
System.out.println(groupMap);

System.out.println("---->>>>List转化为Map>>>----");
//List转化Map
Map<String, Object> map = results.stream().collect(Collectors.toMap(Employee::getName, Employee::getOffice));
map.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));

System.out.println("---->>>>>>>----");
Map<Integer, Employee> employeeMap = results.stream().collect(Collectors.toMap((key -> key.getSalary()), (value -> value)));
employeeMap.forEach((key, value) -> System.out.println(key + "," + value));

System.out.println("---->>遍历map>>>----");
//打印出值大于30的map
Map<String, Integer> resultMap = map_.entrySet().stream().filter(c -> c.getValue() > 30).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
resultMap.forEach((key, value) -> System.out.println(key + "=" + value));

System.out.println(">>>>>>>>>>>>>>>");
//打印key=D的map
Map<String, Integer> mapResults = map_.entrySet().stream().filter(c -> c.getKey().equals("D")).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
mapResults.forEach((key, value) -> System.out.println(key + ">>>>" + value));

System.out.println(">>>>>>>Optional>>>>>>>");
Optional<String> optional = Optional.of("hello");
System.out.println(optional.isPresent());

}

@Test
public void testEmployeeExample() {
//anyMatch
List<Employee> employeeList = generateData();
boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
System.out.println(isMatch);

//allMatch
boolean matched = employeeList.stream().allMatch(employee -> employee.getOffice().equals("London"));
System.out.println(matched);

//找出工资最高的
Optional<Employee> employeeOptional = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
System.out.println(employeeOptional);

//找出工资最少的
Optional<Employee> employee = employeeList.stream().min((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
System.out.println(employee);

//返回姓名列表
List<String> names = employeeList.stream().map(c->c.getName()).collect(Collectors.toList());
System.out.println(names);

System.out.println(">>>>>>>>>>>");
//List转化Map
Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));

//统计办公室是New York的个数
long officeCount = employeeList.stream().filter(c->c.getOffice().equals("New York")).count();
System.out.println(officeCount);

long salaryCount = employeeList.stream().filter(c->c.getSalary()>60000).count();
System.out.println(salaryCount);

//List转化为Set
Set<String> officeSet = employeeList.stream().map(c->c.getOffice()).distinct().collect(Collectors.toSet());
System.out.println(officeSet);

Set<Integer> salarySet = employeeList.stream().map(c->c.getSalary()).distinct().collect(Collectors.toSet());
System.out.println(salarySet);

//查找办公室地点是New York的员工
Optional<Employee> optionals = employeeList.stream().filter(c->c.getOffice().equals("New York")).findAny();
System.out.println(optionals);

System.out.println(">>>>>工资降序排序>>>>>");
//按照工资的降序来列出员工信息
List<Employee> sortSalaryEmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
System.out.println(sortSalaryEmployeeList);

System.out.println(">>>>>姓名升序排序>>>>>");
List<Employee> sortNameEmployeeList = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
System.out.println(sortNameEmployeeList);

System.out.println(">>>>获取工资最高的前2条员工信息");
List<Employee> dispaly2EmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).limit(2).collect(Collectors.toList());
System.out.println(dispaly2EmployeeList);

System.out.println(">>>>获取平均工资");
OptionalDouble averageSalary = employeeList.stream().mapToInt(c->c.getSalary()).average();
System.out.println(averageSalary);

System.out.println(">>>>获取工作地点的平均工资");
OptionalDouble optionalDouble = employeeList.stream().filter(c->c.getOffice().equals("New York")).mapToInt(c->c.getSalary()).average();
System.out.println(optionalDouble);

System.out.println(">>>>>>Java8 Optional用法>>>>>>");
Optional<String> stringOptional = Optional.of("test");
System.out.println(stringOptional.get());

Optional<String> isOptional = Optional.ofNullable("hello");
System.out.println(isOptional.isPresent());
System.out.println(isOptional.get());
System.out.println(isOptional.orElse("0"));

System.out.println(">>>>>>>>>>>>");
//Optional<String> optionalVal = Optional.of(null);
// System.out.println(optionalVal);
Optional<String> optional = Optional.ofNullable("optional");
System.out.println(optional);
System.out.println(optional.isPresent());
System.out.println(optional.get());
System.out.println(optional.orElse("haha"));
System.out.println(">>>>>>>>>>>>");

Optional<Employee> employeeOptional_ = employeeList.stream().filter(c->c.getOffice().equals("New York")).findFirst();
System.out.println(employeeOptional_);

}

stream常用方法

{ %codeblock% }
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.BinaryOperator;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;

/*

  • lambda表达式中
  • 常用的stream相关方法
  • 1.Stream是元素的集合,类似Iterator;
    2.可以支持顺序和并行的对原Stream进行汇聚的操作;
  • @author huitoukest
  • @version 1.0
    /
    public class MainStream {
    /**

    • @param args
      */
      public static void main(String[] args){

      MainStream main=new MainStream();

      //main.testFilter();
      //main.testMap();
      //main.testDistinct();
      //main.testFlatMap();
      //main.testPeek();
      //main.testLimit();
      //main.testCollect();
      //main.testSum();
      main.testReduce();
      

      }

      /**

    • 使用Stream的基本步骤:
      1.创建Stream;
      2.转换Stream,每次转换原有Stream对象不改变,返回一个新的Stream对象(可以有多次转换);
      3.对Stream进行聚合(Reduce/count等等)操作,获取想要的结果;

      如何得到Stream对象:
      

      1.通过Collection接口(实现类)的默认方法stream();
      2.通过Stream接口的静态方法Stream.of,比如Stream stream = Stream.of(1,9,5);
      3.Stream.generate()或者Stream.iterate()生成无限长度的Stream,一般需要用limit(XX)发放来限定长度。

      例子:Stream.iterate(1, item -> item + 1).limit(10).forEach(System.out::println);
                 取出Stream中正整数集合的前10个。
      

      */

      /**

    • filter:过滤操作,将返回值是true的结果对应的项留下。
    • forEach:遍历操作,依次遍历每一个元素。
    • 这里,过滤掉长度大于等于2的元素
      */
      @Test
      public void testFilter(){
      List list=Arrays.asList(“b” ,”1”,”c”,”dd”,”2”);
      list.stream()
      .filter((a)->a.length()<2)
      .forEach((a)->System.out.println(a))
      ;
      }

      /**

    • Map:映射操作,对集合中的每个元素做出相同的更改。
    • 这里,在每个元素后面加入下划线。
      */
      @Test
      public void testMap(){
      List list=Arrays.asList(“b” ,”1”,”c”,”dd”,”2”);
      list.stream()
      .map((a)->a+”_”)
      .forEach((a)->System.out.println(a))
      ;
      }

      /**

    • distinct:集合元素去重复操作。
    • count: 求出集合中元素的数量。
      */
      @Test
      public void testDistinct(){
      List list=Arrays.asList(“1” ,”1”,”2”,”dd”,”2”);
      Long count=list.stream().distinct().count();
      System.out.println(count);
      }

      /**

    • flatMap:和map类似,不同的是其每个元素转换得到的是Stream对象,会把子Stream中的元素压缩到父集合中;
    • 即Map是遍历操作List中的元素。而flatMap中,需要我们返回Stream对象,flatMap自己把(返回的)多个Stream
    • 中的元素遍历压入一个Stream中。
      */
      @Test
      public void testFlatMap(){
      Stream<List> inputStream = Stream.of(

      Arrays.asList(1),
      Arrays.asList(2,3,5),
      Arrays.asList(4,6)
      );
      

      Stream outputStream = inputStream.flatMap((childList) -> childList.stream());
      outputStream.forEach(System.out::println);
      }

      /**

    • Peek:
    • 使用Peek的时候需要传入Consumer(消费函数),同时生成一个新的Stream。
    • 在我们用到新Stream集合中的具体元素的时候,会先触发消费函数中的操作。
      */
      @Test
      public void testPeek(){
      List list=Arrays.asList(“1” ,”a”,”2”,”dd”,”b”);
      list.stream().peek(a->System.out.println(a+”“))
      .forEach((a)->System.out.println(“
      “+a))
      ;
      }

      /**

    • Limit:对一个Stream进行截断操作,获取其前N个元素,如果原Stream中包含的元素个数小于N,那就获取其所有的元素;
    • Skip: 返回一个丢弃原Stream的前N个元素后剩下元素组成的新Stream,如果原Stream中包含的元素个数小于N,那么返回空Stream;
      */
      @Test
      public void testLimit(){
      List list=Arrays.asList(“1” ,”a”,”2”,”dd”,”b”);
      list.stream().limit(4)
      .skip(1)
      .forEach((a)->System.out.println(“_”+a))
      ;
      }

      /**

      上面基本上属于对Stream的转换,遍历,映射等操作。下面则是对Stream的汇聚(Reduce)操作
      

      ***/
      /**

    • 可变汇聚:把输入的元素们累积到一个可变的容器中,比如Collection或者StringBuilder;
      其他汇聚:除去可变汇聚剩下的,一般都不是通过反复修改某个可变对象,
      而是通过把前一次的汇聚结果当成下一次的入参,反复如此。比如reduce,count,allMatch;
      
      */
      /**
    • collect,把Stream中的所有有元素收集到一个结果容器中
    • collect属于可变汇聚,同时也是Stream的通用汇聚操作
      */
      @Test
      public void testCollect(){
      List list=Arrays.asList(“1” ,”a”,”2”,”dd”,”b”);
      /**

      • Collect这里有三个参数,分别是:(生成一个容器,也是返回的容器,如何往容器中添加元素,如何往容器中添加容器中的元素)。
      • */
        ArrayList aList=list.stream().collect(() -> new ArrayList(),
        (lista,b) -> lista.add(b),
        (lista, listb) -> lista.addAll(listb));       
        
        aList.forEach((a)->System.out.println(a))
        ;
        System.out.println();
        /**
      • collect方法也接受Collector参数
      • Collector<T, A, R>
      • T:输入元素类型
      • A:缩减操作的可变累积类型(通常隐藏为实现细节)
      • R:可变减少操作的结果类型
        */
        @SuppressWarnings(“unused”)
        Collector<Integer, ?, TreeSet> intoSet =
        Collector.of(TreeSet::new, TreeSet::add,
                     (left, right) -> { left.addAll(right); return left; });              
        
        System.out.println();
        /**
      • Collectors中封装的一些静态方法返回Collector参数
      • 包括:toList,toSet,toCollection,toMap等等。
        */
        Set aList3=list.stream().collect(Collectors.toSet());
        aList3.forEach((a)->System.out.println(a))
        ;
        }

      /**一些特定的汇聚操作

    • 比如sum,max,count :sum方法不是所有的Stream对象都有的,只有IntStream、LongStream和DoubleStream是实例才有
      */
      @Test
      public void testSum(){
      List list=Arrays.asList(1 ,3,2,0);
      Long sum=list.stream().mapToLong(a->new Long(a)).sum();
      System.out.println(sum);

      System.out.println(list.stream().max((a,b)->a.compareTo(b)).get());
      System.out.println(list.stream().count());
      }

/**
 * Reduce,Reduce是一种通用的方法。
 * Reduce输入两个参数(a,b)——>的到的结果c将会作为下一次迭代的参数a传入,然后直到结束。
 * 
 */
 @Test
public void testReduce(){
    List<Integer> list=Arrays.asList(1 ,3,2,0);
    //(a,b)依次迭代,返回Optional<Integer>
   System.out.println(list.stream().reduce((a,b)->a+b).get());
   //(a,(b,c)->...)附加初始值a,返回a的类型
   System.out.println(list.stream().reduce(-1, (sum, item) ->(sum + item)));
   //计数
   System.out.println(list.stream().reduce(0, (sum, item) ->(sum+1)));
   /**
    * 这里reduce中传入的是BinaryOperator<T>,通过BinaryOperator自带
    * 的maxBy和minBy静态方法可以获得
    */
   System.out.println(list.stream().reduce(
                      BinaryOperator.maxBy((a,b)->a-b)
                      ));
}

/**
 * allMatch:是不是Stream中的所有元素都满足给定的匹配条件
 * 
 */
 @Test
public void testAllMatch(){
    List<Integer> list=Arrays.asList(1 ,3,2,0);
    System.out.println(list.stream().allMatch(a->a>=0));
    System.out.println(list.stream().allMatch(a->a>0));
}
 /**
  * anyMatch:Stream中是否存在任何一个元素满足匹配条件
  * 
  */
  @Test
 public void testAnyMatch(){
     List<Integer> list=Arrays.asList(1,3,2,0);
     System.out.println(list.stream().anyMatch(a->a>100));
     System.out.println(list.stream().anyMatch(a->a>2));
 }
  /**
   * findFirst: 返回Stream中的第一个元素,如果Stream为空,返回空Optional
   */
   @Test
  public void testFindFirst(){
      List<Integer> list=Arrays.asList(1,3,2,0);
      System.out.println(list.stream().findFirst());
      System.out.println(list.stream().findFirst().get());
  }

   /**
    * noneMatch:是不是Stream中的所有元素都不满足给定的匹配条件
    */
    @Test
   public void testNoneMatch(){
       List<Integer> list=Arrays.asList(1,3,2,0);
       System.out.println(list.stream().noneMatch(a->a>100));
       System.out.println(list.stream().noneMatch(a->a>2));
   }
 /**
 * – max和min:使用给定的比较器(Operator),返回Stream中的最大|最小值
 */
}

{ %endcodeblock% }

集合操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
List<Person> list = Lists.newArrayList(
new Person( "张三", 20, new BigDecimal("15000")),
new Person( "李四", 23, new BigDecimal("20000")),
new Person( "王五", 25, new BigDecimal("25000")),
new Person( "赵六", 27, new BigDecimal("30000")),
new Person( "吴七", 30, new BigDecimal("35000"))
);


// 1.计数
long count = list.stream().collect(Collectors.counting());

// 2.最值
Person person = list.stream().collect(Collectors.maxBy(Comparator.comparingInt(Person::getAge))).get();

// 3.求和
int sum = list.stream().collect(Collectors.summingInt(Person::getAge));

// 4.求平均值
double avg = list.stream().collect(Collectors.averagingDouble(Person::getAge));

// 5.一级分组
Map<String, List<Person>> collect = list.stream().collect(Collectors.groupingBy(person -> {
if (person.getAge() >= 30) {
return "30";
} else if (person.getAge() >= 25) {
return "25";
} else {
return "20";
}
}));

// 6.多级分组
Map<String, Map<String, List<Person>>> collect1 = list.stream().collect(Collectors.groupingBy(p -> {
if (p.getAge() >= 30) {
return "30";
} else if (p.getAge() >= 25) {
return "25";
} else {
return "20";
}
}, Collectors.groupingBy(Person::getGender)));

// 7.对分组进行统计
final Map<String, Long> collect2 = list.stream().collect(Collectors.groupingBy(p -> {
if (p.getAge() >= 30) {
return "30";
} else if (p.getAge() >= 25) {
return "25";
} else {
return "20";
}
}, Collectors.counting()));

// 8.将对象集合中的属性转换映射到新的集合
Set<String> names = list.stream().map(Person::getName).collect(Collectors.toSet());

// 9.将对象的一个属性作为 Map 的 key,本身作为 value 映射到 Map 集合
Map<String, Person> empMap1 = list.stream()
.collect(Collectors.toMap(emp -> emp.getName(), Function.identity()));

// 10.将对象的一个属性作为 Map 的 key,另一个属性作为 value 映射到 Map 集合
Map<String, Integer> empMap2 = list.stream()
.collect(Collectors.toMap(emp -> emp.getName(), Person::getAge));

// 11.通过属性过滤数据
List<Person> empList = list.stream()
.filter(emp -> emp.getAge() >= 25 && emp.getAge() <= 30)
.collect(Collectors.toList());

// 12.数值进行求和算数操作,并将结果四舍五入
BigDecimal totalIncome = list.stream()
.map(Person::getIncome)
.reduce(BigDecimal.ZERO, BigDecimal::add)
.setScale(2, BigDecimal.ROUND_HALF_UP);

// 13.单条件排序
List<Person> sortList1 = list.stream().sorted(Comparator.comparing(Person::getAge))
.collect(Collectors.toList());

// 14.多条件排序
List<Person> sortList2 = list.stream().sorted(Comparator.comparing(Person::getAge)
.thenComparing(Person::getIncome).reversed())
.collect(Collectors.toList());