使用流式數據處理檢查list中是否有重復的元素並返回重復元素


public static List<String> getDuplicateElements(List<Dept> list, boolean flag) {
        return list.stream() //
                .map(e -> { // 獲取deptCode或deptAlias的Stream
                    return flag ? e.getDeptCode() : e.getDeptName();
                }).collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) // 獲得元素出現頻率的 Map,鍵為元素,值為元素出現的次數
                .entrySet().stream() // 所有 entry 對應的 Stream
                .filter(entry -> entry.getValue() > 1) // 過濾出元素出現次數大於 1 的 entry
                .map(entry -> entry.getKey()) // 獲得 entry 的鍵(重復元素)對應的 Stream
                .collect(Collectors.toList()); // 轉化為 List
    }

 


免責聲明!

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



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