i have two String list in java and i want to get common element of two list. I use the retainAll method but it doesn't work
String csv = "Apple, Google, Samsung";
List<String> csvList = Arrays.asList(csv.split(","));
ArrayList<String> list0= new ArrayList<String>(csvList);
ArrayList<String> list1 = new ArrayList<String>();
list1.add("Apple");
list1.add("Asus");
list1.add("Lenovo");
list1.add("Google");
list1.retainAll(list0);
list1.retainAll(list0); return list1 empty . list1 must return ==> "Apple, Google, Samsung"
how can i return a list of common element in two string list please help.
CodePudding user response:
The issue is in your input string:
String csv = "Apple, Google, Samsung";
When parsing, spaces are not automatically truncated, so later retainAll
interprets them as different strings, like Google
and Google
.
You can either remove your spaces from the input string or trim them manually.
Correct output for your inputs would be:
[Apple, Google]
CodePudding user response:
Take a look at this: String csv = "Apple, Google, Samsung";
After the split, the second and third elements will be Google
and Samsung
, which are different from Google
and Samsung
.