Java list deduplication with one line of code

Source: Internet
Author: User

Java list deduplication with one line of code
Unsupported Syntax 1. No type Syntax:

List listWithoutDup = new ArrayList(new HashSet(listWithDup));
2. Write the String type ):
1) Java 7:
List
 
   listWithoutDup = new ArrayList
  
   (new HashSet
   
    (listWithDup));
   
  
 
2) Java 7 and above:
List
 
   listWithoutDup = new ArrayList<>(new HashSet<>(listWithDup));
 

Example:
import java.util.ArrayList;import java.util.HashSet;import java.util.List;public class Test {public static void main(String[] args) {List
 
   listWithDup = new ArrayList
  
   ();listWithDup.add("1");listWithDup.add("2");listWithDup.add("3");listWithDup.add("1");List
   
     listWithoutDup = new ArrayList
    
     (new HashSet
     
      (listWithDup));System.out.println("list with dup:"+ listWithDup);System.out.println("list without dup:"+ listWithoutDup);}}
     
    
   
  
 
Sample running result: list with dup: [1, 2, 3, 1]
List without dup: [3, 2, 1]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.