求兩個字符串不相同的數據並輸出

現有兩個字符串

a:"a b c d e",

b:"c d e f k l",

兩字符串中只有小寫字母和空格,求兩個字符串不相同的部分並輸出,比如輸出爲[a, b, f, k, l]

public class Test {

	public static void main(String args[]) {
		String str1 = "a b c d e";
		String str2 = "c d e f k l";
		compare(str1, str2);
	}

	public static void compare(String str1, String str2) {
		List list1 = Arrays.asList(str1.split(" "));
		List list2 = Arrays.asList(str2.split(" "));
		Set<String> set1 = new HashSet<String>(list1);
		Set<String> set2 = new HashSet<String>(list2);
		Set<String> common = new HashSet<>(set1);
		common.retainAll(set2); // 獲取兩集合的交集
		System.out.println(set1);
		System.out.println(common);
		set1.addAll(set2);
		set1.removeAll(common); // 兩集合合併後刪除交集部分
		System.out.println(set1);
	}

}

============================================

若有優化算法,寫在此線下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章