For this I have to take two list as input from user and then I have to compare it. How to do it in java language.
Asked
Active
Viewed 28 times
-2
-
@MuskanVerma you should detail your question. See [this topic](https://stackoverflow.com/help/how-to-ask) – Popovkov57 Oct 12 '22 at 17:41
1 Answers
0
If you want to find common elements between two string ArrayLists
public static ArrayList<String> commonElements(ArrayList<String> a, ArrayList<String> b){
// Initialize arraylist to return
ArrayList<String> toReturn = new ArrayList<String>();
// Iterate across elements of 'a'
for (String s : a){
// If the element is in 'b'
if (b.contains(s)){
// Add it to 'toReturn'
toReturn.add(s);
}
}
return toReturn;
}
Example
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
ArrayList<String> b = new ArrayList<String>();
a.add("hi");
a.add("bye");
a.add("welcome");
a.add("goodbye");
b.add("hi");
b.add("hello");
b.add("goodbye");
for (String s : commonElements(a, b)){
System.out.println(s);
}
}
Output
hi
goodbye

mmartinez04
- 323
- 1
- 1
- 4