LamdaOperate.java
package com.example.demo.util;
import com.example.demo.entity.UserPO;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class LamdaOperate {
public static void test1() {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(1);
int len = list.stream().mapToInt(num -> num).sum();
System.out.println(len);
}
public static void test2() {
List<Integer[]> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Integer[] nums = {1,2};
list.add(nums);
}
int len = list.stream().mapToInt(nums -> nums.length).sum();
System.out.println(len);
}
public static void test3() {
UserPO user1 = new UserPO(1, "java");
UserPO user2 = new UserPO(2, "C");
UserPO user3 = new UserPO(3, "PHP");
List<UserPO> users = new ArrayList<>();
users.add(user1);
users.add(user2);
users.add(user3);
UserPO maxUser = users.stream().max(Comparator.comparing(UserPO::getId)).get();
System.out.println("id = " + maxUser.getId() + ",name = " + maxUser.getName());
}
public static void main(String[] args) {
System.out.println("求和: ");
test1();
System.out.println("\n求数量: ");
test2();
System.out.println("\n获取集合中的最大值: ");
test3();
}
}
UserPO.java
package com.example.demo.entity;
public class UserPO {
private Integer id;
private String name;
public UserPO(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
输出
求和:
4
求数量:
6
获取集合中的最大值:
id = 3,name = PHP