简体   繁体   English

内置方法,用于删除字符串数组中的重复项

[英]Built in method for removing duplicates in a string array

Is there a java built-in method for removing duplicates ? 是否有Java内置方法来删除重复项? ( array of strings ) array of strings

Maybe using a Set ? 也许使用Set in this case how can I use it ? 在这种情况下该如何使用?

Thanks 谢谢

Instead of an array of string, you can directly use a set (in this case all elements in set will always be unique of that type) but if you only want to use array of strings , you can use the following to save array to set then save it back. 您可以直接使用一个set (而不是字符串数组)(在这种情况下,集合中的所有元素将始终是该类型的唯一),但是如果您只想使用array of strings ,则可以使用以下内容保存要set array然后将其保存回来。

import java.util.Arrays;
import java.util.HashSet;

public class HelloWorld{

     public static void main(String []args)
     {
        String dupArray[] = {"hi","hello","hi"};
        dupArray=removeDuplicates(dupArray);

        for(String s: dupArray)
                 System.out.println(s);
     }

    public static String[] removeDuplicates(String []dupArray)
    {
        HashSet<String> mySet = new HashSet<String>(Arrays.asList(dupArray));
        dupArray = new String[mySet.size()];
        mySet.toArray(dupArray);
        return dupArray;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM