Java 实例 - 数组并集

Java 教程 · 2019-02-10 13:43:35

以下实例演示了如何使用 union ()方法来计算两个数组的并集:

Main.java 文件

import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) throws Exception { String[] arr1 = { "1", "2", "3" }; String[] arr2 = { "4", "5", "6" }; String[] result_union = union(arr1, arr2); System.out.println("并集的结果如下:"); for (String str : result_union) { System.out.println(str); } } // 求两个字符串数组的并集,利用set的元素唯一性 public static String[] union(String[] arr1, String[] arr2) { Set<String> set = new HashSet<String>(); for (String str : arr1) { set.add(str); } for (String str : arr2) { set.add(str); } String[] result = { }; return set.toArray(result); } }

以上代码运行输出结果为:

并集的结果如下:
3
2
1
6
5
4

点击查看所有 Java 教程 文章: https://codercto.com/courses/l/12.html

查看所有标签

Programming PHP

Programming PHP

Rasmus Lerdorf、Kevin Tatroe、Peter MacIntyre / O'Reilly Media / 2006-5-5 / USD 39.99

Programming PHP, 2nd Edition, is the authoritative guide to PHP 5 and is filled with the unique knowledge of the creator of PHP (Rasmus Lerdorf) and other PHP experts. When it comes to creating websit......一起来看看 《Programming PHP》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具