IJava Susa iiDVD kuLuhlu

Esi sithuba sinika imizekelo, ebonisa indlela yokususa izinto eziphindiweyo kwiArrayList kwiJava.



Susa iikopi eziphindiweyo kwiArrayList

Ukusukela a Set ayinakubamba izinto eziphindiweyo, sinokuqinisekisa Set Ukugqithisa into kwi-ArrayList kunye neempinda njengeparameter.

Umzekelo:


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);
} }

Iziphumo:

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

Idibeneyo:


Susa iikopi eziphindiweyo kuluhlu

Ngokukwanjalo, sinokusebenzisa indlela efanayo ukususa amanani aphindaphindiweyo.

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);
} }

Iziphumo:

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

Susa iikopi ezivela kuLuhlu usebenzisa iJava 8 yeLaddas

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);
} }

Iziphumo:

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