Java Thoir air falbh dùblaidhean bhon liosta

Tha an dreuchd seo a ’toirt eisimpleirean, a’ sealltainn mar a bheir thu air falbh rudan dùblaichte bho ArrayList ann an Java.



Thoir air falbh sreathan dùblaichte bho ArrayList

Bho a Set chan urrainn dhuinn eileamaidean dùblaichte a chumail, is urrainn dhuinn a Set a chuir sa bhad nì a ’dol seachad air an ArrayList le dùblaidhean mar pharamadair.

Mar eisimpleir:


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

Toradh:

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

Co-cheangailte:


Thoir air falbh integers dùblaichte bhon liosta

San aon dòigh, is urrainn dhuinn an aon dhòigh-obrach a chleachdadh gus integers dùblaichte a thoirt air falbh.



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

Toradh:

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

Thoir air falbh dùblaidhean bhon liosta a ’cleachdadh 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);
} }

Toradh:

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