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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1863957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:18:04  来源:igfitidea点击:

How do I convert an array of strings to a array of unique values?

javaarrays

提问by djangofan

In Java, how do I convert an array of strings to a array of unique values?

在 Java 中,如何将字符串数组转换为唯一值数组?

If I have this array of Strings:

如果我有这个字符串数组:

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

And I want to end up with:

我想结束:

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

采纳答案by Taig

If you're going with the HashSet-approach (which seems pretty handy) you should use a LinkedHashSetinstead of a HashSetif you want to maintain the array's order!

如果您要使用HashSet-approach(这看起来很方便),您应该使用 aLinkedHashSet而不是 aHashSet来维护数组的顺序!

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

回答by ChssPly76

Quick but somewhat inefficient way would be:

快速但有点低效的方法是:

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

回答by djangofan

I tried all the answers on this page and none worked as-is. So, here is how I solved it, inspired by the answers from Taigand akuhn:

我尝试了此页面上的所有答案,但没有一个按原样工作。因此,受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 )

回答by maximdim

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

回答by Stephen C

An alternative to the HashSet approach would be to:

HashSet 方法的替代方法是:

  1. Sort the input array

  2. Count the number of non-duplicate values in the sorted array

  3. Allocate the output array

  4. Iterate over the sorted array, copying the non-duplicate values to it.

  1. 对输入数组进行排序

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

  3. 分配输出数组

  4. 迭代已排序的数组,将非重复值复制到其中。

The HashSet approach is O(N)on average assuming that 1) you preallocate the HashSet with the right size and 2) the (non-duplicate) values in the input array hash roughly evenly. (But if the value hashing is pathological, the worst case is O(N**2)!)

HashSet 方法O(N)平均假设 1) 您预先分配了具有正确大小的 HashSet 和 2) 输入数组中的(非重复)值大致均匀地散列。(但如果值散列是病态的,最坏的情况是O(N**2)!)

The sorting approach is O(NlogN)on average.

排序方法是O(NlogN)平均的。

The HashSet approach takes more memory on average.

HashSet 方法平均需要更多内存。

If you are doing this infrequently ORfor really large "well behaved" input arrays, the HashSet approach is probably better. Otherwise, it could be a toss-up which approach is better.

如果您很少这样做,或者对于非常大的“表现良好”的输入数组,则 HashSet 方法可能更好。否则,这可能是一种折腾,哪种方法更好。

回答by Anon.

An easy way is to create a set, add each element in the array to it, and then convert the set to an array.

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

回答by victor hugo

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

String[] uq = set.toArray();

回答by ThibaudL

Just found a nicer way in Java 8 :

刚刚在 Java 8 中找到了一个更好的方法:

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

回答by Jianfeng Tian

here is my solution:

这是我的解决方案:

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]);
 }
}

回答by Hari

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(" ");
}