java 兩個列表的元素是否相等且各自元素數量相等

吴川华仔博客發表於2024-05-07

示例如下:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("深圳攀峰運","深圳攀峰運","廣州博納德","廣州博納德","廣州博納德","廣州博納德");
        List<String> list2 = Arrays.asList("廣州博納德","廣州博納德","深圳攀峰運","深圳攀峰運","深圳攀峰運","深圳攀峰運");
        
        // 方法一:使用 Collections 類的 frequency 方法
        boolean isEqual = true;
        for (String element : new HashSet<>(list1)) {
            if (Collections.frequency(list1, element) != Collections.frequency(list2, element)) {
                isEqual = false;
                break;
            }
        }

        System.out.println("兩個列表的元素是否相等且各自元素數量相等: " + isEqual);
    }
}

相關文章