如何将一个字符串数组转换为唯一值的数组?

5
在Java中,我如何将一个字符串数组转换为唯一值的数组?
如果我有这个字符串数组:
String[] test = {"1","1","1","2"}

And I want to end up with:

String[] uq = {"1","2"}

使用修改后的归并排序,在遇到重复元素时删除其中一个,而不是将两个副本都添加回列表。运行时间为 **O(N*logN)**。 - recursion.ninja
10个回答

14

一种快速但有些低效的方法是:

Set<String> temp = new HashSet<String>(Arrays.asList(test));
String[] uq = temp.toArray(new String[temp.size()]);

为什么它效率低?考虑到数组可能有超过四个值。另一种选择是对数组进行排序并查找重复项,对吗? - Per Wiklander

5

如果您选择使用 HashSet(这似乎非常方便),那么如果您想保持数组的顺序,应该使用 LinkedHashSet 而不是 HashSet

Set<String> temp = new LinkedHashSet<String>( Arrays.asList( array ) );
String[] result = temp.toArray( new String[temp.size()] );

2

在Java 8中找到了更好的方式:

Arrays.stream(aList).distinct().toArray(String[]::new)

2
String[] test = {"1","1","1","2"};
java.util.Set result = new java.util.HashSet(java.util.Arrays.asList(test));
System.out.println(result);

不需要使用 ""+ 部分,只需要 System.out.println(result) 即可。 - daveb

2

我尝试了这个页面上的所有答案,但都不能直接使用。因此,以下是我如何解决它的方法,受到 Taigakuhn 的启发:

import groovy.io.*;
def arr = ["5", "5", "7", "6", "7", "8", "0"]
List<String> uniqueList = new ArrayList<String>( 
         new LinkedHashSet<String>( arr.asList() ).sort() );
System.out.println( uniqueList )

2
另一种替代HashSet方法的方式是:
  1. 对输入数组进行排序

  2. 计算排序后数组中非重复值的数量

  3. 分配输出数组

  4. 遍历排序后的数组,将非重复值复制到其中。

HashSet方法平均为O(N),前提是1)您使用正确大小预先分配HashSet,2)输入数组中的(非重复)值大致均匀散列。(但如果值哈希成病态情况,则最坏情况为O(N**2)!)
排序方法平均为O(NlogN)
HashSet方法平均需要更多内存。
如果您很少这样做或者处理真正大的“良好 behaved” 输入数组,则HashSet方法可能更好。否则,哪种方法更好可能是随意的。

1
List list = Arrays.asList(test);
Set set = new HashSet(list);

String[] uq = set.toArray();

调用 Set.toArray() 会更容易。 - Anon.
是的,有一会儿我选择了漫长的方式,不知道为什么。 - victor hugo

1

一种简单的方法是创建一个集合(set),将数组中的每个元素添加到集合中,然后将集合转换为数组。


0

这是我的解决方案:

int[] A = {2, 1, 2, 0, 1};

Arrays.sort(A);

ArrayList<Integer> B = new ArrayList<Integer>();

for (int i = 0; i < A.length; i++) {
 if (i == A.length-1) {
    B.add(A[i]);
 }
 else if (A[i] != A[i+1]) {
    B.add(A[i]);
 }
}

0
String[] getDistinctElementsArray(String[] arr){

    StringBuilder distStrings = new StringBuilder();
    distStrings.append(arr[0] + " ");
    for(int i=1;i<arr.length;i++){
        if( arr[i].equals(arr[i-1])){}
        else{
            distStrings.append(arr[i] + " ");
        }
    }
    return distStrings.toString().split(" ");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接