List去重

寫在前面

需求

將totalList中的某些重複記錄移除.(我這裏的totalList中存的是對象)java

思路

是把須要移除的記錄存入removeList,  而後遍歷totalList, 若是totalList中的元素在removeList中, 將該元素從totalList中移除.(土了點, 能用...)spring

由SpringBoot源碼get到的去重技能

(見文章底部)springboot

代碼

            resultList = financeService.selectCaTopupRec(filterMap);//充值記錄
            // 去除重複ref_no的記錄 start==
            if (resultList != null && !resultList.isEmpty()) {
                List<String> needRemoveRefNoList = new ArrayList<>();
                for (CaTopupRec caTopupRec : resultList) {
                    if (caTopupRec.getTopupAmt().compareTo(BigDecimal.ZERO) < 0) {
                        needRemoveRefNoList.add(caTopupRec.getRefNo());
                    }
                }
                if (!needRemoveRefNoList.isEmpty()) {
                    for (Iterator<CaTopupRec> iterator = resultList.iterator(); iterator.hasNext(); ) {
                        CaTopupRec next = iterator.next();
                        if (needRemoveRefNoList.contains(next.getRefNo())) {
                            iterator.remove();
                        }
                    }
                }
            }
            // 去除重複ref_no的記錄 end==

 

List去重黑科技

代碼

下面這行代碼是看SpringBoot自動配置原理時get到的list去重:測試

protected final <T> List<T> removeDuplicates(List<T> list) {
    return new ArrayList(new LinkedHashSet(list));
}

測試

package com.xgcd.springboot;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RemoveDuplicateTest {
    @Test
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        list.add("ddd");
        list.add("aaa");
        for (String str : list) {
            System.out.println(str);
        }

        System.out.println(">>>>>>>>>去重");
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(list);
        ArrayList<String> removeDuplicateList = new ArrayList<>(linkedHashSet);
        for (String str : removeDuplicateList) {
            System.out.println(str);
        }
    }
}

結果

aaa
bbb
ccc
ddd
aaa
>>>>>>>>>去重
aaa
bbb
ccc
dddspa

相關文章
相關標籤/搜索