排序

依据自定义对象的某个属性进行排序.

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

最新文章

  1. 转: 我们为什么使用ORM?
  2. orzdba的安装与使用
  3. ZOJ3550 Big Keng(三分)
  4. mysql数据类型——字符串char(m)和varchar(m)
  5. Linux 下安装包制作
  6. 动手实现linux中的cp命令(可自行拓展)
  7. Material Design5.x动画实现解析篇一
  8. django 模型models
  9. 【BZOJ5491】[HNOI2019]多边形(模拟,组合计数)
  10. 7、Dockerfile详解
  11. MyBatis映射文件1(增删改、insert获取自增主键值)
  12. go logs
  13. Swift 里 Dictionary
  14. 域名DNS解析工具ping/nslookup/dig/host
  15. java中的强,软,弱,虚引用
  16. nodejs遇到的问题
  17. HDU 4632 Palindrome subsequence (区间DP)
  18. Faiss教程:基础
  19. hive组件和执行过程
  20. 记一次服务器迁移SVN客户端更换IP

热门文章

  1. poj 3608(旋转卡壳求解两凸包之间的最短距离)
  2. 虚拟机vmware下安装Ghost XP——正确的解决方案
  3. android studio 设置
  4. (12)python 标准库
  5. Codeforces Round #424 A(模拟)
  6. hdu4757(可持久化 Trie )
  7. mysql 列转行,合并字段的方法
  8. 一种可以做app性能监控的app
  9. 【分块】bzoj3226 [Sdoi2008]校门外的区间
  10. EditText中禁止输入中文的方法