Java 8 List
2024-10-19 03:25:52
排序
依据自定义对象的某个属性进行排序.
List<Student> students = Arrays.asList(student1, student2, student3);
students.sort(Comparator.comparing(Student::getScore).reversed());
students.sort(Collections.reverseOrder(Comparator.comparing(Student::getScore)));
List<Student> sorted = students.stream().sorted(Comparator.comparing(Student::getScore).reversed()).collect(
Collectors.toList());
Java 8 之前版本的排序方法可参考这里: http://stackoverflow.com/a/2784576
分组
分组是将 List
中的对象按照某一属性进行分组并做聚合或统计:
Map<KeyType, List<ClassName>> map1 = List.stream().collect(Collectors.groupingBy(ClassName::getFieldName, Collectors.toList()));
Map<KeyType, Long> map = List.stream().collect(Collectors.groupingBy(ClassName::getFieldName, Collectors.counting()))
分区
将 List
依据某一标准分割为两组.
Map<Boolean, Map<String, Long>> map = students.stream()
.collect(
Collectors.partitioningBy(item -> item.getScore() > 60,
Collectors.groupingBy(Student::getName, Collectors.counting())
)
);
将 List
分割成多个组, 每个组有指定数量的元素(依赖 Apache Commons Collections):
List<List<T>> ListUtils::partition(List<T> list, int size);
List<List<Student>> lists = ListUtils.partition(students, 2);
参考链接:
聚合
求和:
int result = Stream.of(1, 2, 3, 4).sum();
int result = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);
int result = Stream.of(1, 2, 3, 4).reduce(0, (sum, item) -> sum + item);
int result = Stream.of(1, 2, 3, 4).collect(Collectors.summingInt(Integer::intValue));
参考链接:
删除值为 null 的元素
当 List
中有多个 null
元素时, List.remove(null)
只能移除第一个 null
元素, 可使用 List.removeAll(Collections.singletonList(null))
移除所有的 null
元素.
public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
list1.add(null);
list1.add(null);
list1.add("2");
list1.add("3");
list1.remove(null);
System.out.println(list1);//[null, 2, 3]
List<String> list2 = new ArrayList<>();
list2.add(null);
list2.add(null);
list2.add("2");
list2.add("3");
list2.removeAll(Collections.singletonList(null));
System.out.println(list2);//[2, 3]
}
参考链接: Java remove all null elements from list
最新文章
- 转: 我们为什么使用ORM?
- orzdba的安装与使用
- ZOJ3550 Big Keng(三分)
- mysql数据类型——字符串char(m)和varchar(m)
- Linux 下安装包制作
- 动手实现linux中的cp命令(可自行拓展)
- Material Design5.x动画实现解析篇一
- django 模型models
- 【BZOJ5491】[HNOI2019]多边形(模拟,组合计数)
- 7、Dockerfile详解
- MyBatis映射文件1(增删改、insert获取自增主键值)
- go logs
- Swift 里 Dictionary
- 域名DNS解析工具ping/nslookup/dig/host
- java中的强,软,弱,虚引用
- nodejs遇到的问题
- HDU 4632 Palindrome subsequence (区间DP)
- Faiss教程:基础
- hive组件和执行过程
- 记一次服务器迁移SVN客户端更换IP