国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java JavaBase How to prevent duplicate elements in list collection in java

How to prevent duplicate elements in list collection in java

Nov 29, 2019 am 11:30 AM
java element

How to prevent duplicate elements in list collection in java

To process duplicate values ??in the list collection, most of them use two methods. One is to traverse the list collection and then assign it to another list collection, and the other is to use Assigned to the set collection and returned to the list collection. Different methods have their own advantages in different situations.

Related free video tutorial recommendations: java free video tutorial

The code is as follows:

    //set集合去重,不打亂順序
    public static void main(String[] args){
         List<String> list  =   new  ArrayList<String>(); 
         list.add("aaa");
         list.add("bbb");
         list.add("aaa");
         list.add("aba");
         list.add("aaa");

         Set set = new  HashSet(); 
         List newList = new  ArrayList(); 
         for (String cd:list) {
            if(set.add(cd)){
                newList.add(cd);
            }
        }
         System.out.println( "去重后的集合: " + newList); 
      }
     //遍歷后判斷賦給另一個(gè)list集合
     public static void main(String[] args){
         List<String> list  =   new  ArrayList<String>(); 
         list.add("aaa");
         list.add("bbb");
         list.add("aaa");
         list.add("aba");
         list.add("aaa");

         List<String> newList = new  ArrayList<String>(); 
         for (String cd:list) {
            if(!newList.contains(cd)){
                newList.add(cd);
            }
        }
         System.out.println( "去重后的集合: " + newList); 
      }
    //set去重
    public static void main(String[] args){
         List<String> list  =   new  ArrayList<String>(); 
         list.add("aaa");
         list.add("bbb");
         list.add("aaa");
         list.add("aba");
         list.add("aaa");

        Set set = new  HashSet(); 
         List newList = new  ArrayList(); 
         set.addAll(list);
         newList.addAll(set);

         System.out.println( "去重后的集合: " + newList); 
     }
        //set去重(縮減為一行)
        public static void main(String[] args){
             List<String> list  =   new  ArrayList<String>(); 
             list.add("aaa");
             list.add("bbb");
             list.add("aaa");
             list.add("aba");
             list.add("aaa");

             List newList = new ArrayList(new HashSet(list)); 

             System.out.println( "去重后的集合: " + newList); 
         }

hashset does not sort, and another method is to use treeset , remove duplicates and arrange them in natural order, just change hashset to treeset. (The original order has been changed, just arranged in alphabetical order)

//去重并且按照自然順序排列
List newList = new ArrayList(new TreeSet(list));

More related articles and tutorials are recommended: Java zero-based introduction

The above is the detailed content of How to prevent duplicate elements in list collection in java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Implementing Event-Driven Architecture with Java and Apache Kafka Implementing Event-Driven Architecture with Java and Apache Kafka Jul 23, 2025 am 03:51 AM

Understand core components: Producers publish events to Topics, Consumers subscribe and process events, KafkaBroker manages message storage and delivery; 2. Locally build Kafka: Use Docker to quickly start ZooKeeper and Kafka services, expose port 9092; 3. Java integration Kafka: introduce kafka-clients dependencies, or use SpringKafka to improve development efficiency; 4. Write Producer: configure KafkaProducer to send JSON format order events to orders topic; 5. Write Consumer: Subscribe to o through KafkaConsumer

Frontend Build Time Optimization Frontend Build Time Optimization Jul 23, 2025 am 03:37 AM

The core of optimizing front-end build time is to reduce redundant work, improve processing efficiency, utilize caches and select efficient tools. 1. Use TreeShaking and code segmentation reasonably to ensure that it is introduced on demand and dynamic import reduces the packaging volume; 2. Reduce unnecessary loader processing, exclude node_modules, upgrade loaders and relax the scope of Babel translation; 3. Use the caching mechanism to speed up repeated construction, enable Webpack cache, CI cache and use offline installation; 4. Upgrade toolchain, such as using Vite, esbuild or Rollup to improve the construction speed, although there is migration cost, it has significant effect.

Preprocessor Directives in C Preprocessor Directives in C Jul 23, 2025 am 03:45 AM

The preprocessor directive is a command used in C for precompilation processing, and its main functions include header file inclusion, macro definition and conditional compilation. 1.#include is used to introduce header files, standard libraries, customization is used; 2.#define defines macros to implement text replacement, and it is recommended to use const or constexpr instead; 3. Conditional compilation controls whether the code segment is compiled through #ifdef, #ifndef, etc.; 4. Others such as #undef cancellation of macros, #pragma sets compilation options, #error triggers errors, etc. Rational use can improve cross-platform compatibility and debugging efficiency, but macro usage should be reduced to enhance code maintainability.

Surviving the Java Coding Interview: Data Structures and Algorithms Surviving the Java Coding Interview: Data Structures and Algorithms Jul 23, 2025 am 03:46 AM

Master the core data structure and its applicable scenarios, such as the selection of HashMap and TreeMap, and the expansion mechanism of ArrayList; 2. Practice algorithms from the Java perspective, proficient in double pointer, sliding window, DFS/BFS and other modes and can be clearly implemented; 3. Write clean and robust Java code, pay attention to naming, boundary processing and language features (such as generics and final); 4. Prepare the practical question of "why use Java" and understand the impact of StringBuilder, GC, etc. on performance; maintain practice and clear expression to stand out.

python read csv file example python read csv file example Jul 24, 2025 am 01:02 AM

Reading CSV files is commonly implemented in Python using pandas library or csv module. 1. Use pandas to read through pd.read_csv(), return DataFrame, supports specifying parameters such as sep, header, index_col, encoding, na_values, etc., suitable for data analysis; 2. Use the csv module to read line by line through csv.reader or csv.DictReader, the former returns a list, and the latter returns a dictionary, suitable for lightweight or no dependencies of third-party libraries; 3. Frequently asked questions: Use a complete path to avoid path errors, set encoding='gbk' or 'utf-8' to solve Chinese

python count items in list example python count items in list example Jul 24, 2025 am 02:58 AM

Use len() to count the total number of elements in the list, such as len([1,2,3,4,5]) to return 5; 2. Use count() to count the number of occurrences of specific elements, such as ['apple','banana','apple'].count('apple') to return 3; 3. Use collections.Counter to count the frequency of each element, such as Counter(['a','b','a']) to output Counter({'a':3,'b':2,'c':1}); 4. Use dictionary to manually count the traversal and get methods to achieve the same effect, such as loop accumulation to obtain {'a':3,'b':2,'c':1}.

Java Data Structures and Algorithms for Performance Java Data Structures and Algorithms for Performance Jul 23, 2025 am 03:09 AM

The key to optimizing Java program performance lies in the rational selection of data structures and algorithms. 1. Select appropriate collection classes according to the scene, such as frequent access to intermediate elements, use ArrayList, and use LinkedList to operate head or tail, find multi-priority HashMap or HashSet, and avoid thread-safe classes and capacity expansion losses. 2. Avoid repeated calculations, use memory cache results to reduce time complexity. 3. Master efficient sorting search algorithms, such as insertion sorting, counting sorting, binary search, KMP, etc., and select according to data characteristics. 4. Reduce GC pressure, avoid creating objects in loops, use object pools, StringBuilder and use StreamAPI with caution.

Understanding Screen Resolution, Refresh Rate, and Response Time Understanding Screen Resolution, Refresh Rate, and Response Time Jul 23, 2025 am 03:18 AM

The screen resolution determines the clarity. 1080p is suitable for daily use below 24 inches. 1440p or 4K is recommended for better experience over 27 inches. 2. The refresh rate affects the smoothness of the picture. 60Hz is suitable for office work, 144Hz and above is suitable for gaming and dynamic operations. 3. The response time is related to the sharpness of the dynamic picture. 1ms is suitable for competitive games, 4-5ms meets daily and ordinary game needs, and avoids more than 8ms to prevent striking.

See all articles