Lambda常⽤写法
1、排序
import lombok.Data;
import java.util.*;
import java.util.stream.Collectors;
public class StreamStudy {
public static void main(String[] args) {
User u1 = new User("陈⼀",32);
User u2 = new User("陈⼆",23);
User u3 = new User("陈三",33);
List<User> users = new ArrayList<>();
users.add(u1);
users.add(u2);
users.add(u3);
List<User> collect1 = users.stream().sorted(Comparatorparing(User::getAge)).List());
System.out.println(collect1);
List<User> collect2 = users.stream().sorted(Comparatorparing(User::getAge).reversed()).List());        System.out.println(collect2);
}
}
@Data
class User {
public User() {}
public User(String name, int age) {
this.name = name;
this.age = age;
}
String name;
int age;
}
2、集合操作
import lombok.Data;
import java.util.*;
import java.util.stream.Collectors;
public class StreamStudy {
public static void main(String[] args) {
User user1 = new User(5, "aa");
User user2 = new User(2, "ba");
User user3 = new User(3, "ac");
User user4 = new User(1, "aad");
User user5 = new User(4, "asd");
List<User> userList = Arrays.asList(user1, user2, user3, user4, user5);
//获取所有ID集合
List<Integer> idList = userList.stream().map(User::getId).List());
System.out.println(idList);
//根据ID排序
List<User> userList1 = userList.stream().sorted(ComparatorparingInt(User::getId)).List());
System.out.println(userList1);
sortedlist//分组
Map<String, Long> map = userList.stream().upingBy(User::getName, unting()));
System.out.println(map);
//获取id⼤于2的
List<User> userList2 = userList.stream().filter(user -> Id() > 2).List());
System.out.println(userList2);
//获取最⼤
Integer id = userList.stream().map(User::getId).max(Integer::compareTo).get();
System.out.println(id);
//获取最⼩
Integer id1 = userList.stream().map(User::getId).min(Integer::compareTo).get();
System.out.println(id1);
//获取数量
Long id3 = userList.stream().count();
System.out.println(id3);
//求和
int sum = userList.stream().mapToInt(User::getId).sum();
System.out.println(sum);
//获取平均值
double avg = userList.stream().mapToInt(User::getId).average().getAsDouble();
System.out.println(avg);
//如果存在获取任意⼀个对象
User user = userList.stream().filter(us -> us.getId() > 2).findAny().get();
System.out.println(user);
//获取第⼀个对象
User userFirst = userList.stream().findFirst().get();
System.out.println(userFirst);
/
/将名字全转换为⼤写
List<String> upName = userList.stream().map(User::getName).map(String::toUpperCase).List());
System.out.println(upName);
//获取忽略第⼀个并取前⼏条数据
List<User> users = userList.stream().skip(1).limit(2).List());
System.out.println(users);
//去重
List<User> userDis = userList.stream().distinct().List());
System.out.println(userDis);
}
}
@Data
class User {
public User(){}
public User(int id, String name){
this.id = id;
this.name = name;
}
int id;
String name;
}
3、并⾏流
将List转为Map
Map<Long, DeviceOnlineDto> onlinemap = onlinelist.parallelStream().Map(DeviceOnlineDto::getDeviceid, e -> e));

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。