常用语法示例:
public static void main(String[] args) {
List<OrderInfo> orderInfoList = Lists.newArrayList();
List<OperateInfo> operateInfoList = Lists.newArrayList(); //operateInfoList转map(key:operateId value:operateName)
Map<Integer, String> operateMap = operateInfoList.stream().collect(Collectors.
toMap(OperateInfo::getOperateId, OperateInfo::getOperateName, (x, y) -> x)); //orderInfoList分组(key:type value:List<OrderInfo>)
Map<Integer, List<OrderInfo>> orderInfoGroup = orderInfoList.stream()
.filter(order -> order.getType() != null)
.collect(Collectors.groupingBy(OrderInfo::getType)); List<List<OrderInfoResponse>> result = new ArrayList<>();
orderInfoGroup.values().forEach(list -> {
//根据orderId递减
list = list.stream().sorted(Comparator.comparing(OrderInfo::getOrderId).reversed()).collect(Collectors.toList()); //List<OrderInfo>转List<OrderInfoResponse>
List<OrderInfoResponse> responses = list.stream().map(order -> {
OrderInfoResponse response = new OrderInfoResponse();
response.setOrderId(order.getOrderId());
response.setTypeName(OrderTypeEnum.getNameByCode(order.getType()));
response.setCreatorName(operateMap.get(order.getCreatorId()));
return response;
}).collect(Collectors.toList());
result.add(responses);
}); //orderInfoList第一个type为TYPE1的对象
OrderInfo orderInfo = orderInfoList.stream()
.filter(order -> OrderTypeEnum.TYPE1.getCode().equals(order.getType()))
.findFirst().orElse(null);
}
Bean:
@Data
public class OrderInfo {
private Integer id;
private Integer type;
private Integer operatorId;
}
@Data
public class OrderInfoResponse {
private Integer id;
private Integer type;
private String typeName;
private Integer operatorId;
private String operatorName;
}
@Data
public class OperatorInfo {
private Integer operatorId;
private String operatorName;
}
public enum OrderTypeEnum {
TYPE1(1,"类型1"),
TYPE2(2,"类型2"); private Integer code;
private String name; OrderTypeEnum(Integer code, String name) {
this.code = code;
this.name = name;
} public Integer getCode() {
return code;
}
public String getName() {
return name;
} public static String getNameByCode(Integer code) {
for (OrderTypeEnum typeEnum : OrderTypeEnum.values()) {
if (typeEnum.code.equals(code)) {
return typeEnum.name;
}
}
return "";
}
}
util:
@Slf4j
public class Safes {
public static <T> List<T> of(List<T> source) {
return (List)Optional.ofNullable(source).orElse(Lists.newArrayListWithCapacity(0));
} public static <T> Set<T> of(Set<T> source) {
return (Set)Optional.ofNullable(source).orElse(Sets.newHashSetWithExpectedSize(0));
}
}
tips:
1,list集合为null时,list.stream()会抛异常。用 Safes.of() 方法将集合由null转为空集合。