项目中运用到的Lambda表达式,简化了Java8以前的写法,包含了循环、判断、求和、分组等。边学边做,记录如下:
1、计算JSON字符串中value的sum值(map)
public static void main(String[] args) {
String test = "{\"0\":4,\"1\":1,\"2\":105,\"3\":135,\"4\":132,\"5\":6,\"6\":0}";
Map<Integer, Integer> map = JSON.parseObject(test, Map.class);
Integer sum = map.values()
.stream()
.reduce(Integer::sum)
.orElse(0);
System.out.println(sum);
}
2、在List<Dto>中过滤某个指定key的数据(filter)
Java8之前要先循环列表,然后再list.contains()
public class DeviceUserBaseLineDto{
private String device_id;
private String deviceUserDtoStr ;
}
public static void main(String[] args) {
String deviceId = "123";
List<DeviceUserBaseLineDto> collect = deviceUserBaseLineDtos
.stream()
.filter(a ->deviceId.equals(a.getDevice_id())).collect(Collectors.toList());
//此处a->后可以多条件
String deviceUserDtoStr = collect.get(0).getDeviceUserDtoStr();
}
3、提取List<Dto>中的某个属性成集合
//从对象列表中提取一列(以name为例)
List<String> nameList = userList.stream().map(UserInfo::getName).collect(Collectors.toList());
//提取后输出name
nameList.forEach(s-> System.out.println(s));
4、key=value数组转Map
String[] array = ["startTime"="2018-10-13 14:14:14","endTime"="2018-10-13 14:14:14"];
Map<String, Object> kvs = new HashMap<>();
Arrays.asList(array).stream().map(elem -> elem.split("=")).forEach(elem -> kvs.put(elem[0], elem[1]));