1

how do I check if an object of an arraylist matches with another one no matter the order of the elements and their number of occurrences. let's say I have:

obj1   contains    "boy",  "girl",  "kid"
obj2   contains     "girl",   "kid",  "boy", "girl"
obj3   contains     "woman",  "boy",  "girl",   "kid"

all of arraylist

I want the program to achieve this:

obj1    =     obj2   true
obj1    =     obj3   false
obj2    =     obj3   false
4
  • 1
    And what you have tried till now?? Commented Mar 4, 2014 at 14:02
  • 3
    Sounds more like a Set than a List. Commented Mar 4, 2014 at 14:03
  • refer- stackoverflow.com/questions/16386278/… Commented Mar 4, 2014 at 14:07
  • Convert both lists to Sets, find the intersection of the sets and check if it has the same size as the original sets. Commented Mar 4, 2014 at 14:08

3 Answers 3

3

I think that you mean the following. You want to check whether unique elements contained in your lists are the same. The order does not matter.

To solve this problem you need set that contain only unique elements and do not preserve order:

List<String> first = ....
List<String> second = ....

boolean result = new HashSet<>(first).equals(new HashSet<>(second));
Sign up to request clarification or add additional context in comments.

Comments

1

You should use containsAll() method:

    List a = Arrays.asList("boy", "girl", "kid");
    List b = Arrays.asList("girl", "kid", "boy", "girl");
    List c = Arrays.asList("woman", "boy", "girl", "kid");

    System.out.println(a.containsAll(b));     // true
    System.out.println(a.containsAll(c));     // false
    System.out.println(b.containsAll(c));     // false

Comments

0

Just to get you started, read about List .contains method. Use it in nested loops with boolean flag to indicate whether one list item satisfies .equals to any item in other list.

You will also need to decide whether comparison should be two way. You may have a scenario where all items of obj1 are present in obj2, but all items of obj2 are not present in obj1. In other words, obj2 is a superset of obj1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.