Delete duplicate strings in string array

后端 未结 13 2021
执念已碎
执念已碎 2020-12-30 00:33

I am making a program based on string processing in Java in which I need to remove duplicate strings from a string array. In this program, the size of all strings are same.

相关标签:
13条回答
  • 2020-12-30 00:45
    Set<String> set = new HashSet<String>();
    Collections.addAll(set, array);
    

    or start with

    for(int s=0;s<array.length-1;s++)
    {
        for(int m=s + 1;m<array.length;m++)
        {
    
                    if(array[s] != null && array[s].equals(array[m]))
                    {
                      // array = ArrayUtils.removeElement(array, array[s]); --m;??
                      array[m] = null; // Mark for deletion later on
                    }
        } 
    }
    
    0 讨论(0)
  • 2020-12-30 00:45
    List<String> al = new ArrayList<String>();
    String[] months={"Jan","Feb","Mar","Apr","Jan","Mar","May","May"};
    for(int i=0;i<months.length;i++){
        for(int j=1;j<months.length;j++){
            if(months[i].equalsIgnoreCase(months[j])){
                if(!al.contains(months[i])){
                    al.add(months[i]);
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-30 00:45

    Set data structure will do automatically the job for. Most likely option for you will be HashSet, if you care about the order of elements look at TreeSet

    List<String> input = Arrays.asList(array);
    Set<String> unique = new HashSet<>(input);
    
    0 讨论(0)
  • 2020-12-30 00:46

    Proposed solution does not keep the order of the elements. If you use Java 8 or higher and want to maintain the order you can use streams as follows:

    array = Arrays.stream(array).distinct().toArray(String[]::new);
    

    Full example: https://www.javacodeexamples.com/java-string-array-remove-duplicates-example/849

    0 讨论(0)
  • 2020-12-30 00:50
         String[] arr = {"w10","w20","w10","w30","w20","w40","w50","w50"};
         List<String> arrList = new ArrayList<String>();
         int cnt= 0;
           //List<String> arrList = Arrays.asList(arr);
           List<String> lenList = new ArrayList<String>();
              for(int i=0;i<arr.length;i++){
            for(int j=i+1;j<arr.length;j++){
               if(arr[i].equals(arr[j])){
                 cnt+=1;
               }                
            }
            if(cnt<1){
              arrList.add(arr[i]);
            }
              cnt=0;
            }
    
    for(int k=0;k<arrList.size();k++){
                System.out.println("Array without Duplicates: "+arrList.get(k));
            }
    
    0 讨论(0)
  • 2020-12-30 00:52

    This will work

    array = new HashSet<String>(Arrays.asList(array)).toArray(new String[0]);
    

    or just use a HashSet instead of an array.

    0 讨论(0)
提交回复
热议问题