数组和列表去重方法:数组去重:使用 Set 转换或 ArrayList 转 Set 再转数组。列表去重:使用 LinkedHashSet 保留插入顺序或使用 Set 转换或 ArrayList 转 Set 再转 ArrayList。

Java 数组和列表去重
数组去重
<code class="java">int[] arr = {1, 2, 3, 4, 5, 1, 2};
Set<Integer> uniqueSet = new HashSet<>(Arrays.asList(arr));</code><code class="java">int[] arr = {1, 2, 3, 4, 5, 1, 2};
List<Integer> uniqueList = new ArrayList<>(Arrays.asList(arr));
int[] uniqueArray = uniqueList.stream().distinct().toArray();</code>列表去重
<code class="java">List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 1, 2); LinkedHashSet<Integer> uniqueSet = new LinkedHashSet<>(list); List<Integer> uniqueList = new ArrayList<>(uniqueSet);</code>
<code class="java">List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 1, 2); Set<Integer> uniqueSet = new HashSet<>(list); List<Integer> uniqueList = new ArrayList<>(uniqueSet);</code>
<code class="java">List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 1, 2);
List<Integer> uniqueList = new ArrayList<>();
for (Integer num : list) {
if (!uniqueList.contains(num)) {
uniqueList.add(num);
}
}</code>以上就是java数组和列表怎么去重的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号