唯一元素的数组? [英] Array of unique elements?
本文介绍了唯一元素的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个像下面这样的数组,我想知道是否有一种简单的方法可以将这个数组变成一个只有唯一值的数组?
Given an array like the one below, I was wondering if there is an easy way to turn this array into an array with unique values only?
这是给定的:
numbers={5,5,4,3,1,4,5,4,5}
把它变成这样的结果数组,保持原来的顺序:
Turn it into a result array like this, preserving the original order:
{5,1,2,3,4}
推荐答案
在 Java 8 中,使用 IntStream
获取数组的唯一元素
In Java 8, use IntStream
to get unique elements of an array
int[] noDuplicates = IntStream.of(array).distinct().toArray();
<小时>
最简单的方法是从数组创建集合.
The simplest way would be to create set from the array.
Integer[] array = ...
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(array ));
然后您可以使用以下方法检索数组:
and then you can retrieve the array using:
set.toArray()
如果要保持顺序,请使用LinkedHashSet,如果要对其进行排序,请使用TreeSet.
use LinkedHashSet if you want to maintain the order or TreeSet if you want to have it sorted.
这篇关于唯一元素的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文