-5

I am trying to write a program and I have two arraylists and I want to check if they contain a component that is the same in both.

For example:

arraylist1 {steve, bob, alex, jeff}
arraylist2 {jack, jeff, chris, jake}

since jeff is in both the program would print jeff.

Kruti Patel
  • 1,422
  • 2
  • 23
  • 36
BMW
  • 33
  • 1
  • 9
  • I am stuck at a stand still so I have not tried anything thus far. – BMW Feb 22 '16 at 05:00
  • before proceeding to work with ArrayList you must check out the documentation for it on following link https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html – Mr. Noddy Feb 22 '16 at 05:09

3 Answers3

0

You can compare each element of this arraylist to each element of that arraylist.if they equal you will print...you can use for each loop.

tdv39
  • 1
0

A very straightforward but slow approach: (I know there must be faster methods)

Loop through the first list. For each item in that list, loop through the second list to see if there are any item that is the same as the first one.

public static boolean areListsSimilar(ArrayList<String> list1, ArrayList<String> list2) {
    for (item1 : list1) {
         for (item2 : list2) {
             if (item1.equals(item2)) return true;
         }
    }
    return false;
}

Or you can do this (ArrayList instead of ArrayList<String>)

public static boolean areListsSimilar(ArrayList list1, ArrayList list2) {
    for (item1 : list1) {
         for (item2 : list2) {
             if (item1.equals(item2)) return true;
         }
    }
    return false;
}

Or add generic constraints to only accepts the arguments that implement Equatable

public static <T> boolean areListsSimilar(ArrayList<? extends Equatable> list1, ArrayList<? extends Equatable> list2) {
    for (item1 : list1) {
         for (item2 : list2) {
             if (item1.equals(item2)) return true;
         }
    }
    return false;
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0
public String[] search(ArrayList<String> alphas, ArrayList<String> betas) {
    ArrayList<String> results = new ArrayList<String>();    // Create container for results

    // Search for results
    for (String alpha : alphas) {
        for (String beta : betas) {
            if (alpha.equals(beta)) {
                results.add(alpha);
                break;
            }
        }
    }

    // Return results
    return results.toArray(new String[results.size()]);
}
ifly6
  • 5,003
  • 2
  • 24
  • 47