求两个字符串不相同的数据并输出

现有两个字符串

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);
	}

}

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

若有优化算法,写在此线下

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