如何从数组中获取唯一值

时间:2021-04-09 12:41:52

I have an Array from which i want to remove Duplicate items.

我有一个数组,我想从中删除重复的项。

for(int data1=startpos;data1<=lastrow;data1++) {
    String movie_soundtrk=cells.getCell(data1,Mmovie_sndtrk_cl).getValue().toString();
    al.add(movie_soundtrk);
}

String commaSeparated=al.toString();
String [] items = commaSeparated.split(",");
String[] trimmedArray = new String[items.length];
for (int i = 0; i < items.length; i++) {
    trimmedArray[i] = items[i].trim();
}

Set<String> set = new HashSet<String>();
Collections.addAll(set, trimmedArray);

System.out.println(set);

But this is not giving me unique Values from Array.

但这并没有给出数组的唯一值。

My Array:- {English, French, Japanese, Russian, Chinese Subtitles,English, French, Japanese, Russian, Chinese Subtitles}

我的数组:-{英文,法文,日文,俄文,中文字幕,英文,法文,日文,俄文,中文字幕}

Out Put :- [Japanese, Russian, French, Chinese Subtitles], Chinese Subtitles, [English, English]

输出:-[日语,俄语,法语,中文字幕],中文字幕,[英语,英语]

7 个解决方案

#1


34  

You can do it in one line in java 7:

你可以在java 7中一行完成:

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

and shorter and simpler in java 8:

java 8更短更简单:

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

#2


3  

HashSet will do the job.

HashSet将执行此任务。

You can try this:

你可以试试这个:

List<String> newList = new ArrayList<String>(new HashSet<String>(oldList));

#3


1  

Using the Stream API of Java 8 this is a solution with a generic Array type:

使用Java 8的流API,这是一个具有通用数组类型的解决方案:

public static <T> T[] makeUnique(T... values)
{
    return Arrays.stream(values).distinct().toArray(new IntFunction<T[]>()
    {

        @Override
        public T[] apply(int length)
        {
            return (T[]) Array.newInstance(values.getClass().getComponentType(), length);
        }

    });
}

It works for any Object type array, but not for primitive arrays.

它适用于任何对象类型数组,但不适用于原始数组。

For primitive arrays it looks like this:

对于原始数组,它是这样的:

public static int[] makeUnique(int... values)
{
    return Arrays.stream(values).distinct().toArray();
}

And finally here is a little unit test:

最后是一个小单元测试

@Test
public void testMakeUnique()
{
    assertArrayEquals(new String[] { "a", "b", "c" }, makeUnique("a", "b", "c", "b", "a"));
    assertArrayEquals(new Object[] { "a", "b", "c" }, makeUnique(new Object[] { "a", "b", "c", "b", "a" }));
    assertArrayEquals(new Integer[] { 1, 2, 3, 4, 5 }, makeUnique(new Integer[] { 1, 2, 2, 3, 3, 3, 1, 4, 5, 5, 5, 1 }));
    assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, makeUnique(new int[] { 1, 2, 2, 3, 3, 3, 1, 4, 5, 5, 5, 1 }));
}

#4


0  

You could get two sets, one with all the subtitles, and the other with the duplicates

您可以得到两个集合,一个带有所有的子标题,另一个带有副本。

String[] trimmedArray = new String[items.length];
Set<String> subtitles = new HashSet<String>();
Set<String> duplicatedSubtitles = new HashSet<String>();

foreach(String subtitle : trimmedArray){
    subtitle = subtitle.trim();
    if(subtitles.contains(subtitle)){
        duplicatedSubtitles.add(subtitle);
    }
    subtitles.add(subtitle);
}

#5


0  

Try instead of this

尝试相反的

Set<String> set = new HashSet<String>();

to call this

调用这个

set.addAll(trimmedArray);

#6


0  

Why did you first add items into array and then convert it to string? Just iterate over tha array and copy them to Set.Then print new created set which holds unique values.

为什么要首先将项目添加到数组中,然后将其转换为字符串?只需遍历该数组并将其复制到set .然后打印包含唯一值的新创建集。

Set<String> set = new HashSet<String>();
for (int i = 0; i < al.length; i++) {
    set.add(al[i]);
}

for (String str : set) {
    System.out.println(str);
}

#7


0  

This code will calculates distinct elements from an array, then finds their occurrence. And calculates percentage and save it to hashmap.

这段代码将从数组中计算出不同的元素,然后找到它们的出现。并计算百分比并保存到hashmap。

int _occurrence = 0;
        String[] _fruits = new String[] {"apple","apple","banana","mango","orange","orange","mango","mango","banana","banana","banana","banana","banana"};
        List<String> _initialList = Arrays.asList(_fruits);
        Set<String> treesetList = new TreeSet<String>(_initialList);
        String[] _distinct =  (String[]) treesetList.toArray(new String[0]);

        HashMap<String,String> _map = new HashMap<String,String>();
        int _totalElement = _fruits.length;
        for(int x=0;x<_distinct.length;x++){
            for(int i=0;i<_fruits.length;i++){
                if(_distinct[x].equals(_fruits[i])){
                    ++_occurrence;
                }
            }
            double _calPercentage = Math.round((((double)_occurrence/(double)_totalElement)*100));
            _map.put(_distinct[x], String.valueOf(_calPercentage+"%"));
            _occurrence = 0;
        }
        System.out.println(_map);

#1


34  

You can do it in one line in java 7:

你可以在java 7中一行完成:

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

and shorter and simpler in java 8:

java 8更短更简单:

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

#2


3  

HashSet will do the job.

HashSet将执行此任务。

You can try this:

你可以试试这个:

List<String> newList = new ArrayList<String>(new HashSet<String>(oldList));

#3


1  

Using the Stream API of Java 8 this is a solution with a generic Array type:

使用Java 8的流API,这是一个具有通用数组类型的解决方案:

public static <T> T[] makeUnique(T... values)
{
    return Arrays.stream(values).distinct().toArray(new IntFunction<T[]>()
    {

        @Override
        public T[] apply(int length)
        {
            return (T[]) Array.newInstance(values.getClass().getComponentType(), length);
        }

    });
}

It works for any Object type array, but not for primitive arrays.

它适用于任何对象类型数组,但不适用于原始数组。

For primitive arrays it looks like this:

对于原始数组,它是这样的:

public static int[] makeUnique(int... values)
{
    return Arrays.stream(values).distinct().toArray();
}

And finally here is a little unit test:

最后是一个小单元测试

@Test
public void testMakeUnique()
{
    assertArrayEquals(new String[] { "a", "b", "c" }, makeUnique("a", "b", "c", "b", "a"));
    assertArrayEquals(new Object[] { "a", "b", "c" }, makeUnique(new Object[] { "a", "b", "c", "b", "a" }));
    assertArrayEquals(new Integer[] { 1, 2, 3, 4, 5 }, makeUnique(new Integer[] { 1, 2, 2, 3, 3, 3, 1, 4, 5, 5, 5, 1 }));
    assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, makeUnique(new int[] { 1, 2, 2, 3, 3, 3, 1, 4, 5, 5, 5, 1 }));
}

#4


0  

You could get two sets, one with all the subtitles, and the other with the duplicates

您可以得到两个集合,一个带有所有的子标题,另一个带有副本。

String[] trimmedArray = new String[items.length];
Set<String> subtitles = new HashSet<String>();
Set<String> duplicatedSubtitles = new HashSet<String>();

foreach(String subtitle : trimmedArray){
    subtitle = subtitle.trim();
    if(subtitles.contains(subtitle)){
        duplicatedSubtitles.add(subtitle);
    }
    subtitles.add(subtitle);
}

#5


0  

Try instead of this

尝试相反的

Set<String> set = new HashSet<String>();

to call this

调用这个

set.addAll(trimmedArray);

#6


0  

Why did you first add items into array and then convert it to string? Just iterate over tha array and copy them to Set.Then print new created set which holds unique values.

为什么要首先将项目添加到数组中,然后将其转换为字符串?只需遍历该数组并将其复制到set .然后打印包含唯一值的新创建集。

Set<String> set = new HashSet<String>();
for (int i = 0; i < al.length; i++) {
    set.add(al[i]);
}

for (String str : set) {
    System.out.println(str);
}

#7


0  

This code will calculates distinct elements from an array, then finds their occurrence. And calculates percentage and save it to hashmap.

这段代码将从数组中计算出不同的元素,然后找到它们的出现。并计算百分比并保存到hashmap。

int _occurrence = 0;
        String[] _fruits = new String[] {"apple","apple","banana","mango","orange","orange","mango","mango","banana","banana","banana","banana","banana"};
        List<String> _initialList = Arrays.asList(_fruits);
        Set<String> treesetList = new TreeSet<String>(_initialList);
        String[] _distinct =  (String[]) treesetList.toArray(new String[0]);

        HashMap<String,String> _map = new HashMap<String,String>();
        int _totalElement = _fruits.length;
        for(int x=0;x<_distinct.length;x++){
            for(int i=0;i<_fruits.length;i++){
                if(_distinct[x].equals(_fruits[i])){
                    ++_occurrence;
                }
            }
            double _calPercentage = Math.round((((double)_occurrence/(double)_totalElement)*100));
            _map.put(_distinct[x], String.valueOf(_calPercentage+"%"));
            _occurrence = 0;
        }
        System.out.println(_map);