嘿,我想按名称对照片进行排序,首先我想要所有包含“个人资料”一词的照片,然后按 ABC 比较其余的照片
目前我只按名称排序
photos
.stream()
.sorted(Comparator.comparing(Photo::getFileName))
.collect(Collectors.toList());
我怎样才能实现这一目标?谢谢
最佳答案
编写逻辑来确定排序“优先级”,值越低,优先级越高,例如
- 0 = 包含“个人资料”
- 1 = 其他所有内容
然后先按优先级排序,然后再按名称排序。
在下面的示例中,我们使用正则表达式进行不区分大小写的“包含”检查,并对其进行预编译以获得更好的性能。
Pattern containsProfile = Pattern.compile("profile", Pattern.CASE_INSENSITIVE);
photos.stream()
.sorted(Comparator.comparingInt((Photo p) -> containsProfile.matcher(p.getFileName()).find() ? 0 : 1)
.thenComparing(Photo::getFileName))
.collect(Collectors.toList());
关于java排序如果包含然后按abc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65302745/