package cn.yuhui.com;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class jaccard {
public static void main(String[] args) {
work();
}
public static void work(){
List<String> liOne = new ArrayList<String>();
liOne.add("a b c d");
liOne.add("e g i w");
liOne.add("c j k x");
liOne.add("d k r y");
liOne.add("q r s t");
liOne.add("u v w x");
liOne.add("g n u v");
liOne.add("c d e f");
liOne.add("a h i j");
liOne.add("k l m n");
List<String> liTwo = new ArrayList<String>();
liTwo.add("a h o v");
liTwo.add("b i p w");
liTwo.add("c j q x");
liTwo.add("d k r y");
liTwo.add("e l s z");
liTwo.add("f m w x");
liTwo.add("g n u v");
liTwo.add("c d e f");
liTwo.add("g h i j");
liTwo.add("a l m o");
for (int i = 0; i < liOne.size(); i++) {
String[] arr1 = liOne.get(i).split(" ");
String[] arr2 = liTwo.get(i).split(" ");
relativelycompare(arr1 , arr2);
}
}
public static void relativelycompare(String[] arr1 ,String[] arr2 ){
System.out.print("File01内容为:");
ArrayToPrin(arr1);
System.out.print(" || File02内容为:");
ArrayToPrin(arr2);
//求两个数组的交集
Map<String, Boolean> map = new HashMap<String, Boolean>();
LinkedList<String> listjiaoji = new LinkedList<String>();
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 (Entry<String, Boolean> e : map.entrySet()) {
if (e.getValue().equals(Boolean.TRUE)) {
listjiaoji.add(e.getKey());
}
}
System.out.print(" || 交集为:");
ListToPrin(listjiaoji);
//求两个字符串数组的并集,利用set的元素唯一性
List<String> listbingji = new ArrayList<String>();
Set<String> set = new HashSet<String>();
for (String str : arr1) {
set.add(str);
}
for (String str : arr2) {
set.add(str);
}
Iterator<String> iterator1 = set.iterator();
while(iterator1.hasNext()){
listbingji.add(iterator1.next());
}
System.out.print(" || 并集为:");
ListToPrin(listbingji);
//求两个数组的差集
LinkedList<String> chaji = new LinkedList<String>();
LinkedList<String> history = new LinkedList<String>();
String[] longerArr = arr1;
String[] shorterArr = arr2;
//找出较长的数组来减较短的数组
if (arr1.length > arr2.length) {
longerArr = arr2;
shorterArr = arr1;
}
for (String str : longerArr) {
if (!chaji.contains(str)) {
chaji.add(str);
}
}
for (String str : shorterArr) {
if (chaji.contains(str)) {
history.add(str);
chaji.remove(str);
} else {
if (!history.contains(str)) {
chaji.add(str);
}
}
}
System.out.print(" ||差集为:");
ListToPrin(chaji);
System.out.println();
}
public static void ListToPrin(List<String> list){
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i)+" ");
}
}
public static void ArrayToPrin(String[] arr){
for (String str : arr) {
System.out.print(str+" ");
}
}
}
JAVA程序:字符串数组交集、并集和差集
最新推荐文章于 2024-10-03 10:58:56 发布