Java Mbusak Duplikat Saka Dhaptar

Kiriman iki menehi conto, nuduhake cara mbusak item duplikat saka ArrayList ing Java.



Copot String Duplikat Saka ArrayList

Wiwit Set ora bisa nahan elemen duplikat, kita bisa nginstal Set obyek sing liwati ing ArrayList kanthi duplikat minangka parameter.

Contone:


import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.Set; public class RemoveDuplicatesFromArrayList {
public static void main(String[] args) {
ArrayList pets = new ArrayList();

pets.add('cat');
pets.add('dog');
pets.add('cat');
pets.add('hamster');

System.out.println(pets);

Set hashSet = new LinkedHashSet(pets);
ArrayList removedDuplicates = new ArrayList(hashSet);

System.out.println(removedDuplicates);
} }

Output:

[cat, dog, cat, hamster] [cat, dog, hamster]

Gegandhengan:


Copot Integer Duplikat Saka Dhaptar

Kajaba iku, kita bisa nggunakake metodologi sing padha kanggo mbusak bilangan bulat.



import java.util.*; public class RemoveDuplicatesFromArrayList {
public static void main(String[] args) {
List numbers = Arrays.asList(1,2,2,2,3,5);

System.out.println(numbers);

Set hashSet = new LinkedHashSet(numbers);
ArrayList removedDuplicates = new ArrayList(hashSet);

System.out.println(removedDuplicates);
} }

Output:

[1, 2, 2, 2, 3, 5] [1, 2, 3, 5]

Mbusak Duplikat Saka Dhaptar Nggunakake Java 8 Lambdas

import java.util.*; import java.util.stream.Collectors; public class RemoveDuplicatesFromArrayList {
public static void main(String[] args) {
List numbers = Arrays.asList(1,2,2,2,3,5);

System.out.println(numbers);

List removedDuplicates = numbers.stream()


.distinct()


.collect(Collectors.toList());

System.out.println(removedDuplicates);
} }

Output:

[1, 2, 2, 2, 3, 5] [1, 2, 3, 5]