List根據對象屬性去重 && List根據數量分組


List根據對象屬性去重 && List根據數量分組

List根據對象屬性去重

現有一個Student類,類中有一個name屬性,需要根據name屬性對一個裝有Student的list進行去重:

Student
public class Student {
    private String name;

    public Student() { }

    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

現在有一個裝有Student的list:

List<Student> list = new ArrayList<>();
Collections.addAll(list,
        new Student("張三"),
        new Student("李四"),
        new Student("王五"),
        new Student("張三"),
        new Student("李四"),
        new Student("趙六"));

System.out.println("去重之前: ");
System.out.println("list = " + list);
/* 輸出:
去重之前: 
list = [張三, 李四, 王五, 張三, 李四, 趙六]
*/

第一種方式:

ArrayList<Student> afterList = list.stream()
        .collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getName())))
                , ArrayList::new));

System.out.println("第一種去重之后: ");
System.out.println("afterList = " + afterList);
/* 輸出:
第一種去重之后: 
afterList = [張三, 李四, 王五, 趙六]
*/

第一眼看到這段代碼愣是沒看懂這是在去重,寫成下面這種方式比較好理解:

第二種方式:

Set<Student> set = new TreeSet<>(Comparator.comparing(Student::getName));
set.addAll(list);
List<Student> afterList2 = new ArrayList<>(set);

System.out.println("第二種去重之后: ");
System.out.println("afterList2 = " + afterList2);
/* 輸出:
第二種去重之后: 
afterList2 = [張三, 李四, 王五, 趙六]
*/

其原理都是利用TreeSet的構造方法:public TreeSet(Comparator<? super E> comparator)(JDK 1.8)來進行去重處理,並且可以根據多個屬性來去重。

這里我特意看了一下HashSet,發現HashSet並沒有類似構造方法,也就是說根據屬性去重必須使用TreeSet

List根據數量分組

有時候需要把一個list拆分成多個list分批處理,這時候可以使用這種方式:

List<String> list = new ArrayList<>();
Collections.addAll(list, "1", "2", "3", "4", "5", "6", "7", "8");
List<List<String>> resultList = new ArrayList<>();

//多少個一組
int groupNum = 3;

//當前游標
int current = 0;
while (current < list.size()) {
    resultList.add(new ArrayList<>(list.subList(current, Math.min((current + groupNum), list.size()))));
    current += groupNum;
}

System.out.println("resultList = " + resultList);
/* 輸出:
resultList = [[1, 2, 3], [4, 5, 6], [7, 8]]
*/

這里使用了list.subList(fromIndex, toIndex)這個方法(范圍包頭不包尾,因此toIndex可以直接使用list.size()),需要注意的是,subList()方法返回的是源list的視圖,而非一個新的ArrayList,對subList進行添加刪除操作會影響到源list,因此subList需要作為new ArrayList<>(subList)的參數來添加到resultList里面。


類似的坑還有一個Arrays.asList()方法,使用Arrays.asList()獲得的List對象不能添加刪除元素,因此一般也是作為new ArrayList<>(Arrays.asList(array))的參數來使用,這也是常用的數組轉List


免責聲明!

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



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