0

I have two lists, in one list values are 1,2,3

another list 2,3

I want to remove the values which are not matched in both lists.

2 and 3 are matched in both lists then 1 is not mached in both lists so I want to remove that value.

List original = [1,2,3];

List dummy = [2,3];
user9130953
  • 449
  • 2
  • 13

3 Answers3

3

If it's possible to use sets instead, then you can just get the intersection between the sets (info):

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

Of course with sets you can't have duplicates and you'll lose ordering.

Mark
  • 18,730
  • 7
  • 107
  • 130
  • A `LinkedHashSet` even would maintain the insert order. And duplicates seem not to be conceived. So this is indeed a fine solution. – Joop Eggen May 26 '18 at 10:05
  • 1
    This answer changes the requirement (if the two lists contain `1`, it is not asked that we have only a single 1 as result) and it changes also the elements order. The question is "I want to remove the values which are not matched in both lists." – davidxxx May 26 '18 at 10:10
  • @davidxxx That was already clearly stated in the answer, but thanks for emphasizing – Mark May 26 '18 at 10:28
1

You don't need to use a Set to achieve your requirement.
Use retainAll() defined in Collection that any List implementation implements such as :

List<Integer> original = new ArrayList<>(Arrays.asList(1,2,3));
List<Integer> dummy = Arrays.asList(2,3);

original.retainAll(dummy);
System.out.println(original);

Output :

[2, 3]

davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

If you are using Java 8+ you can use :

original.removeIf(a -> !dummy.contains(a));

Here is an example with Java 10

var original = new ArrayList<>(List.of(1, 2, 3, 4));
var dummy = new ArrayList<>(List.of(2, 4, 3));

original.removeIf(a -> !dummy.contains(a));

System.out.println(original);
->[2, 3, 4]
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140