简体   繁体   中英

Differences Between Two Integer Collection

I have two set of integers(ie first one is: 2,3,4,5 and second one is 1,2,3,6). How can I found the addition numbers array(1,6) and subtracted numbers array(4,5)? I said collection but I keep them at Set however if you have any other idea, I can use it too. I will keep addition numbers and subtracted numbers within different collections too.

I assume you mean elements in one set but not the other.

Set<Integer> first = new LinkedHashSet<Integer>(Arrays.asList(2,3,4,5));
Set<Integer> second = new LinkedHashSet<Integer>(Arrays.asList(1,2,3,6));
Set<Integer> addition = subtract(first, second);
Set<Integer> subtracted = subtract( second, first);

public static <T> Set<T> subtract(Set<T> set1, Set<T> set2) {
    Set<T> ret = new LinkedHashSet<T>(set1);
    ret.removeAll(set2);
    return ret;
}

Not sure whether that's what you need but you can use google guava for that:

import java.util.HashSet;
import java.util.Set;

import com.google.common.collect.Sets;


public class NumbersTest {

    public static void main(String[] args) {
        Set<Integer> set1 = new HashSet<Integer>(){{add(2);add(3);add(4);add(5);}};
        Set<Integer> set2 = new HashSet<Integer>(){{add(1);add(2);add(3);add(6);}};
        System.out.println("Nums Unique to set1: " + Sets.difference(set1, set2));
        System.out.println("Nums Unique to set2: " + Sets.difference(set2, set1));
    }
}

Outputs:

Nums Unique to set1: [4, 5]
Nums Unique to set2: [1, 6]

Definitely not the best solution, but though..

public class IntsFind {
public static void main(String[] args) {
    List<Integer> first = Arrays.asList(2, 3, 4, 5);
    List<Integer> second = Arrays.asList(1, 3, 4, 6);

    List<Integer> missing = new LinkedList<Integer>();
    List<Integer> added = new LinkedList<Integer>(second);

    for (Integer i : first) {
        if (!added.remove(i)) {
            missing.add(i);
        }
    }

    System.out.println("Missing ints in second: " + missing);
    System.out.println("New ints in second: " + added);
}

}

Prints:

Missing ints in second: [2, 5] New ints in second: [1, 6]

EDIT No need to wrap Arrays.asList, as pointed by @Peter Lawrey

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM