Remove Duplicate from a List in Java
public class Main {
public static void main(String[] args) {
// remove duplicates from a list
List < Integer > list = Arrays.asList(1, 2, 3, 2, 3, 1, 4, 1);
/*System.out.println("------ With Java 8 -------");
System.out.println(list.stream().distinct().collect(Collectors.toList()));*/
System.out.println("------ Without Java 8 -------");
List < Integer > l = new ArrayList < > ();
for (int i = 0; i < list.size(); i++) {
if (l.contains(list.get(i)) != true) {
l.add(list.get(i));
}
}
System.out.println(l);
}
}
==========================================================
Output
[1,2,3,4]
Comments
Post a Comment