목록에서 중복을 제거하는 코드는 다음과 같습니다 -
예시
import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.Set; public class Demo { public static void main(String[] args){ ArrayList<String> list = new ArrayList<String>(); list.add("Jacob"); list.add("Gary"); list.add("Gary"); list.add("Harry"); list.add("Harry"); list.add("Kevin"); System.out.println("List = "+list); Set<String> set = new LinkedHashSet<String>(list); System.out.println("List after removing duplicate elements = "+set); } }
출력
List = [Jacob, Gary, Gary, Harry, Harry, Kevin] List after removing duplicate elements = [Jacob, Gary, Harry, Kevin]
예시
이제 다른 예를 살펴보겠습니다 -
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Demo { public static void main(String[] args){ List<String> list = new ArrayList<String> (Arrays.asList("Ryan","Kevin","Ryan","Harry","Mark","Mark")); System.out.println("ArrayList = "+list); List<String> list2 = list.stream() .distinct() .collect(Collectors.toList()); System.out.println("Updated ArrayList without duplicates = "+list2); } }
출력
ArrayList = [Ryan, Kevin, Ryan, Harry, Mark, Mark] Updated ArrayList without duplicates = [Ryan, Kevin, Harry, Mark]