Java Bvisa zvakapetwa Kubva Chinyorwa

Iyi posvo inopa mienzaniso, inoratidza maitiro ekubvisa zvakapetwa zvinhu kubva kuArrayList muJava.

Bvisa Duplicate Tambo Kubva ArrayList

Sezvo Set haikwanise kubata zvakapetwa zvinhu, tinogona kusimbisa Set chinhu chinopfuura muArrayList nemaviri separamende.

Semuyenzaniso:

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

Kubuda:

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

Inoenderana:

Bvisa Duplicate Integer Kubva Chinyorwa

Saizvozvo, isu tinokwanisa kushandisa nzira imwecheteyo yekubvisa zvakapetwa manhamba.



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

Kubuda:

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

Bvisa zvakapetwa kubva pane Rondedzero Uchishandisa 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);
} }

Kubuda:

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