亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java中ArrayList的交并

Java中ArrayList的交并

回首憶惘然 2019-07-02 10:34:01
Java中ArrayList的交并是否有辦法這樣做?我在找,但找不到。另一個問題:我需要這些方法來過濾文件。有些是AND過濾器和一些是OR過濾器(就像集合論中的那樣),所以我需要根據所有文件和保存這些文件的UnitedArrayList/Intersects ArrayList進行過濾。我應該使用不同的數據結構來保存文件嗎?還有什么能提供更好的運行時的嗎?
查看完整描述

3 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

這里是一個沒有使用任何第三方庫的簡單實現。主要優勢retainAllremoveAlladdAll這些方法不修改輸入到方法的原始列表。

public class Test {

    public static void main(String... args) throws Exception {

        List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
        List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));

        System.out.println(new Test().intersection(list1, list2));
        System.out.println(new Test().union(list1, list2));
    }

    public <T> List<T> union(List<T> list1, List<T> list2) {
        Set<T> set = new HashSet<T>();

        set.addAll(list1);
        set.addAll(list2);

        return new ArrayList<T>(set);
    }

    public <T> List<T> intersection(List<T> list1, List<T> list2) {
        List<T> list = new ArrayList<T>();

        for (T t : list1) {
            if(list2.contains(t)) {
                list.add(t);
            }
        }

        return list;
    }}


查看完整回答
反對 回復 2019-07-02
?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

收藏(ArrayList也是如此)有:

col.retainAll(otherCol) // for intersectioncol.addAll(otherCol) // for union

如果接受重復,則使用列表實現;如果不接受重復,則使用SET實現:

Collection<String> col1 = new ArrayList<String>(); // {a, b, c}

// Collection<String> col1 = new TreeSet<String>();

col1.add("a");

col1.add("b");

col1.add("c");


Collection<String> col2 = new ArrayList<String>(); // {b, c, d, e}

// Collection<String> col2 = new TreeSet<String>();

col2.add("b");

col2.add("c");

col2.add("d");

col2.add("e");


col1.addAll(col2);

System.out.println(col1); 

//output for ArrayList: [a, b, c, b, c, d, e]

//output for TreeSet: [a, b, c, d, e]


查看完整回答
反對 回復 2019-07-02
?
達令說

TA貢獻1821條經驗 獲得超6個贊

這篇文章相當古老,但它是谷歌在尋找這個話題時第一次出現。

我想使用Java 8流(基本上)在一行中進行相同的更新:

List<T> intersect = list1.stream()
    .filter(list2::contains)
    .collect(Collectors.toList());List<T> union = Stream.concat(list1.stream(), list2.stream())
    .distinct()
    .collect(Collectors.toList());

如果有人有更好/更快的解決方案,請告訴我,但是這個解決方案是一個很好的線性程序,可以很容易地包含在方法中,而無需添加不必要的助手類/方法,并且仍然保持可讀性。


查看完整回答
反對 回復 2019-07-02
  • 3 回答
  • 0 關注
  • 800 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號