java 两个数组取交集_java对两个字符串数组取交集、并集和差集

直接上代码。

import java.util.*;

public class StringArrayUtil {

// 求两个字符串数组的并集,利用set的元素唯一性

public static String[] union(String[] arr1, String[] arr2) {

Set set = new HashSet<>();

Collections.addAll(set, arr1);

Collections.addAll(set, arr2);

String[] result = {};

return set.toArray(result);

}

// 求两个数组的交集

public static String[] intersect(String[] arr1, String[] arr2) {

Map map = new HashMap<>();

LinkedList list = new LinkedList<>();

for (String str : arr1) {

if (!map.containsKey(str)) {

map.put(str, Boolean.FALSE);

}

}

for (String str : arr2) {

if (map.containsKey(str)) {

map.put(str, Boolean.TRUE);

}

}

for (Map.Entry e : map.entrySet()) {

if (e.getValue().equals(Boolean.TRUE)) {

list.add(e.getKey());

}

}

String[] result = {};

return list.toArray(result);

}

// 求两个数组的差集

public static String[] minus(String[] arr1, String[] arr2) {

LinkedList list = new LinkedList<>();

LinkedList history = new LinkedList<>();

String[] longerArr = arr1;

String[] shorterArr = arr2;

// 找出较长的数组来减较短的数组

if (arr1.length > arr2.length) {

longerArr = arr2;

shorterArr = arr1;

}

for (String str : longerArr) {

if (!list.contains(str)) {

list.add(str);

}

}

for (String str : shorterArr) {

if (list.contains(str)) {

history.add(str);

list.remove(str);

} else {

if (!history.contains(str)) {

list.add(str);

}

}

}

String[] result = {};

return list.toArray(result);

}

}

字符串数组的操作在平常的业务开发中用得比较多,是每个Java开发者都应当掌握的技能。

"大人的每一次流泪,都是一场无声的孤独。"

来源:https://www.cnblogs.com/yanggb/p/12798160.html

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值