如何从数组中获取唯一项? [英] How to get unique items from an array?
本文介绍了如何从数组中获取唯一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Java 初学者,我找到了一些关于这个主题的主题,但没有一个对我有用.我有一个这样的数组:
I am Java beginner, I found a few topics regarding this theme, but none of them worked for me. I have an array like this:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
我需要得到这个输出:
1, 2, 3, 4, 5
该数组中的每个项目仅一次.
Every item from that array just once.
但是如何获得呢?
推荐答案
最简单的解决方案,无需编写自己的算法:
The simpliest solution without writing your own algorithm:
Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);
设置接口保证值的唯一性.TreeSet 还对这些值进行排序.
Set interface guarantee uniqueness of values. TreeSet additionally sorts this values.
这篇关于如何从数组中获取唯一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文