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開發者都應當掌握的技能。

 

"大人的每一次流淚,都是一場無聲的孤獨。"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM