Using java 8

package com.logical.programming.prime;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

public class Example {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList();
list.add("1");
list.add("2");
list.add("2");
list.add("3");
list.add("4");
list.add("4");
list.add("5");
list.add("5");

HashSet set = new HashSet();

List l1 = list.stream().filter(n -> !set.add(n)).collect(Collectors.toList());
System.out.println(set); o/p [1, 2, 3, 4, 5]
System.out.println(l1); o/p [2, 4, 5]

}

}

[1, 2, 3, 4, 5]
[2, 4, 5]
duplicate element

Second Method Using Java 7

package com.logical.programming.prime;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Example {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList();
list.add("1");
list.add("2");
list.add("2");
list.add("3");
list.add("4");
list.add("4");
list.add("5");
list.add("5");

// HashSet set = new HashSet();
//
// List l1 = list.stream().filter(n -> !set.add(n)).collect(Collectors.toList());
// // System.out.println("Output for set" + set);
// // System.out.println("Dublicate list" + l1);

Set set = new HashSet();
List list2 = new ArrayList<>();

for (int i = 0; i < list.size(); i++) {

if (set.contains(list.get(i))) {

// System.out.println("DUblicate" + list.get(i));
list2.add(list.get(i));

} else {
set.add(list.get(i));
}
}
System.out.println(set);
System.out.println(list2);

}

}

o/p
[1, 2, 3, 4, 5]
[2, 4, 5]

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

No responses yet