1

I have two arraylists and I want to remove identical values between these lists, but only one occurrence of this. For example:

ArrayList<Integer> a = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
ArrayList<Integer> b = new ArrayList<>(Arrays.asList(1,2,3,1,2,3));

With these, function unique(a,b) would return:

[[4,5,6],[1,2,3]]
3
  • 4
    Have you tried something so far? Commented Dec 7, 2016 at 0:15
  • 1
    You need them as separate lists is it like [4,5,6],[1,2,3] ? or as a single [1,2,3,4,5,6]? Commented Dec 7, 2016 at 0:17
  • are you using java 8? Commented Dec 7, 2016 at 0:19

3 Answers 3

2

Assuming you want to return an ArrayList of ArrayLists, you can achieve this using this method:

private static ArrayList<ArrayList<Integer>> unique(ArrayList<Integer> a, ArrayList<Integer> b) {
    ArrayList<ArrayList<Integer>> unique = new ArrayList<>();

    unique.add(new ArrayList<>());
    unique.add(new ArrayList<>());


    for (Integer i: a) {
        if (!b.contains(i) && !unique.get(0).contains(i)) {
            unique.get(0).add(i);
        }
    }

    for (Integer i: b) {
        if (a.contains(i) && !unique.get(1).contains(i)) {
            unique.get(1).add(i);
        }
    }

    return unique;
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you only need to know the unique elements in a bunch of lists:

public static <T> ArrayList getUnique(List<T> ... lists){
  Set<T> unique = new HashSet<T>();
  for (List<T> eachList : lists){
    unique.addAll(eachList);
  }
  return new ArrayList(unique);
}

And you can call it like this:

List<Integer> unique = getUnique(a,b);

Comments

0

@lmiguelvargasf - I took your function and modified it a little because it turns out your version only works if the numbers are all different already. Here is the new function:

private static ArrayList<ArrayList<Integer>> unique(ArrayList<Integer> a, ArrayList<Integer> b) {
    ArrayList<ArrayList<Integer>> unique = new ArrayList<>();
    unique.add(new ArrayList<>());
    unique.add(new ArrayList<>());

    for (Integer i: a) {
        if (!b.contains(i)) {
            unique.get(0).add(i);
        }else{
            b.remove(i);
        }
    }

    for (Integer i: b) {
        if (!a.contains(i)) {
            unique.get(1).add(i);
        }else{
            b.remove(i);
        }
    }

    return unique;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.