Java 8 List


排序

依據自定義對象的某個屬性進行排序.

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM