zoukankan      html  css  js  c++  java
  • java对两个字符串数组取交集、并集和差集

    直接上代码。

    import java.util.*;
    
    public class StringArrayUtil {
        // 求两个字符串数组的并集,利用set的元素唯一性
        public static String[] union(String[] arr1, String[] arr2) {
            Set<String> 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<String, Boolean> map = new HashMap<>(); LinkedList<String> 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<String, Boolean> 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<String> list = new LinkedList<>(); LinkedList<String> 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开发者都应当掌握的技能。

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

  • 相关阅读:
    随机性的控制
    856. 括号的分数
    376. 摆动序列(贪心算法)
    XGBoost 安装方法
    1405. 最长快乐字符串(贪心算法)
    1296. 划分数组为连续数字的集合(贪心算法)
    1353. 最多可以参加的会议数目(贪心算法)
    435. 无重叠区间(贪心算法)
    Array-数组-数据结构
    认识Redis和安装
  • 原文地址:https://www.cnblogs.com/yanggb/p/12798160.html
Copyright © 2011-2022 走看看