集合排序使用 stream的sorted方法 通过方法引用指定排序的字段
list.sort(Comparator.comparing(QuestionHisOptionDto::getOptionNo));
倒序 使用 sorted 跟 reversed; 并去重
ArrayList<ExamRecordsBean> examRecords = examRecordsBeans.stream().sorted(Comparator.comparing(ExamRecordsBean::getExamScore).reversed())
.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(ExamRecordsBean::getCreator))), ArrayList::new));
集合根据某一个字段去重复
通过treeset来去重,多个参数的话,后面添加多个方法引用
List<RoleMenuTreeDto> menuTreeDtos = roleMenuTreeDtos.stream()
.collect(Collectors
.collectingAndThen(Collectors.toCollection(()
-> new TreeSet<>(Comparator.comparing(RoleMenuTreeDto::getId))), ArrayList::new));
多个字段去重
List<ExamAnswerRecord> answerRecordCreators = answerRecords.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getCreator() + ";" + o.getQuestionHisRefId()))), ArrayList::new));
对象集合string字段按int排序
list.sort(Comparator.comparing(对象::属性).thenComparing(this::compare));
public int compare(对象 对象1, 对象 对象2) {
return Integer.compare(Integer.parseInt(对象1.get属性()), Integer.parseInt(对象2.get属性()));
}
@Override
public List<PointNumVo> monitorPointNumList(MonitorNumReq bo) {
LambdaQueryWrapper<EquipmentPoint> lqw = buildQueryWrapper(EquipmentPointBo.builder()
.workSurfaceNum(bo.getWorkSurfaceNum())
.monitoringType(bo.getMonitoringType())
.build());
List<EquipmentPoint> equipmentPoints = baseMapper.selectPointList(lqw);
return equipmentPoints.stream().map(point -> PointNumVo.builder()
.monitorPointNum(point.getMonitorPointNum())
.installPosition(point.getInstallPosition())
.build()).sorted(Comparator.comparing(PointNumVo::getInstallPosition, this::stringCompare)).toList();
}
/**
* 排序
* @param s1
* @param s2
* @return {@link Integer}
*/
public Integer stringCompare(String s1, String s2) {
String regex = "\\d+";
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher1 = pattern.matcher(s1);
Matcher matcher2 = pattern.matcher(s2);
if (matcher1.find() && matcher2.find()) {
String group1 = matcher1.group();
String group2 = matcher2.group();
if (Integer.parseInt(group1) > Integer.parseInt(group2)) {
// 降序
return 1;
} else {
// 升序
return -1;
}
}
return 0;
}
reduce统计
Arrays.stream(numbers).map(Integer::valueOf).reduce(0, Integer::sum);
public static void main(String[] args) {
List<Integer> arrayList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
System.out.println(arrayList); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
/**
* 求和
*/
Integer sum = arrayList.stream().reduce(Integer::sum).orElse(0);
System.out.println(sum); // 45
/**
* 求最大值
*/
Integer max = arrayList.stream().reduce(Integer::max).orElse(0);
System.out.println(max); // 9
/**
* 求最小值
*/
Integer min = arrayList.stream().reduce(Integer::min).orElse(0);
System.out.println(min); // 1
/**
* 逻辑运算
* 求最小值
*/
Integer num = arrayList.stream()
.reduce((pre, pro) -> pre > pro ? pro : pre)
.orElse(0);
System.out.println(num); // 1
}
两个集合根据集合字段筛选
List<User> list = Lists.newArrayList();
User user1 = User.builder().userId("1").build();
User user2 = User.builder().userId("2").build();
list.add(user1);
list.add(user2);
List<String> userIds = Lists.newArrayList();
userIds.add("0");
userIds.add("2");
list = list.stream()
.filter(userGet -> !userIds.contains(userGet.getUserId())).collect(Collectors.toList());
list.forEach(System.out::println);
https://www.cnblogs.com/snidget/p/11892097.html
j截取
查询多少个
list.stream().limit().
跳过几个查询
list.stream().skip().
时间分组
时间工具类
public class LocalDateTimeUtil {
public static String parse2yyyyMm(LocalDate time) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy年MM月");
return df.format(time);
}
public static LocalDate toLocalDate(String time) {
time = time + "01日";
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
LocalDate localDate = LocalDate.parse(time, df);
return localDate;
}
}
时间分组排序
Map<String, List<ThreeDimensionalVo>> dateMap = list.stream()
.collect(Collectors.groupingBy(date -> LocalDateTimeUtil.parse2yyyyMm(date.getTime()), TreeMap::new, Collectors.toList()));
list.stream().collect(Collectors.groupingBy(RealTimeVo::getCreateTime, TreeMap::new, Collectors.toList()));
Map<String, List<BusinessStatisticEntity>> monthMap = areaList.stream()
.collect(Collectors.groupingBy(month -> LocalDateTimeUtil.parse2yyyyMm(month.getStatisticData())));
jdk8 合并list
-----数据
[{gailun=盖伦},{zhaoxin=赵信},{ruiwen=瑞文}]
-----目标
{gailun=盖伦,zhaoxin=赵信,ruiwen=瑞文}
第一种
List<Map<String,Object>> lists=new ArrayList<>();
Map<String, Object> merged = new HashMap<>();
lists.forEach(merged::putAll);
第二种
// 不想覆盖,保留最初的值:
List<Map<String,Object>> lists=new ArrayList<>();
lists.stream().flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a));
// 覆盖key相同的值:
List<Map<String,Object>> lists=new ArrayList<>();
lists.stream().flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));
分组后 转换别的对象
Map<UserRelationTypeEnum, List<AreaReq>> listMap = list.stream()
.collect(Collectors.groupingBy(UserAreaRelationEntity::getRelationType,
Collectors.mapping(AreaAuthConvertUtils::toAreaReq, Collectors.toList())));
jdk8 按字段分组后根据key排序
参考链接
要点
- jdk流表达式
- 使用TreeMap排序
- 使用new Comparator 方法
Map<String, List<BusinessStatisticEntity>> monthMap = areaList.stream()
.sorted(Comparator.comparing(BusinessStatisticEntity::getStatisticData).reversed())
.collect(Collectors.groupingBy(month -> LocalDateTimeUtil.parse2yyyyMm(month.getStatisticData()), () -> {
return new TreeMap<>((o1, o2) -> {
// 这里是我字符串时间类型转时间类型
LocalDate start = LocalDateTimeUtil.parse2yyyyMmToDate(o1);
LocalDate end = LocalDateTimeUtil.parse2yyyyMmToDate(o2);
// 降序升序选择一种
if (end.isAfter(start)){
//降序
return 1;
}
if (end.isAfter(start)) {
// 升序
return -1;
}
return 0;
});
}, Collectors.toList()));
函数式变成
peek跟foreach区别
peek循环完还是流 foreach 循环完输出
function跟Consumer 区别
function有返回值 Consumer 无返回值
function跟Bifunction区别
function 传入一个参数返回
Bifunction 传入两个参数返回
BinaryOperator、 BiFunction区别
BiFunction 传入两个参数返回
BinaryOperator 传入三个参数类型相同
的参数返回相同类型的返回值
apply方法
接收参数返回
accept方法
接收参数 无返回值
predicate 理解
predicate可以搭配jdk8 stream的filter使用
单独编写 predicate 的方法 或者判断 复制在filter 的参数中使用
public class PredicateTest extends ECommerceGatewayApplicationTests {
public static List<String> MICRO_SERVICE = Arrays.asList(
"nacos", "authority", "gateway", "ribbon", "feign", "hystrix", "e-commerce"
);
@Test
public void testPredicateTest() {
Predicate<String> letterLengthLimit = s -> s.length() > 5;
MICRO_SERVICE.stream().filter(letterLengthLimit).forEach(System.out::println);
}
}
枚举类函数式参数的使用场景
根据类型返回不同数据
Class<?> clazz = tempData.getClass();
Field[] fields = clazz.getDeclaredFields();
String filedName = "passagewayValue%s";
AtomicReference<String> currNameFer = new AtomicReference<>(filedName);
for (String pipelineNum : pipelineNums) {
Field field = Arrays.stream(fields).filter(filed -> String.format(currNameFer.get(), pipelineNum).equals(filed.getName())).findFirst().get();
field.setAccessible(true);
try {
double zValue = (Double) field.get(tempData);
tempValue = tempValue.add(BigDecimal.valueOf(zValue));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}