简体   繁体   中英

comparing two arraylist with condition in Java

I have printed two array lists from two CSV files

CSV 1 to arraylist

BufferedReader br = new BufferedReader(new  InputStreamReader(stream));
String text = br.readLine();
String[] b = text.split(String.valueOf(str));
csv1.add(b[0]);

CSV 2 to arraylist

BufferedReader br = new BufferedReader(new  InputStreamReader(stream));
String text = br.readLine();
String[] b = text.split(String.valueOf(str));
csv2.add(b[0]);

I need to compare column names but they are labelled differently in each file. column John in list 1 is equal to col smith in list 2

ArrayList1 = ["John","Jane","Vehicle","Snack","Ring"]
ArrayList2 = ["Car","Bar","Smith","Doe","Ring"]

For example; John in list1 has all the same data as smith in list2. I need to check if John is present in list one, then smith SHOULD be present in list 2 and check for that column name.

The method takes two lists and two supplied strings and checks to see if both strings appear in opposing lists.

public boolean checkName(List<String> list1, List<String> 
    list2, String one, String two) {
     return list1.contains(one) && list2.contains(two) ||
            list1.contains(two) && list2.contains(one);
}

You could use a map if you know which column names are linked to each other.

Map<String,String> map = new HashMap<>();
map.put("John", "Smith");
map.put("Jane", "Doe");
map.put("Vehicle", "Car");
map.put("Snack", "Bar");
map.put("Ring", "Ring");

EDIT

Assuming you have read the content of the files into lists as given in your example and your list contain:

//code to read file content into lists
//....

ArrayList1 = ["John","Jane","Vehicle","Snack","Ring"]
ArrayList2 = ["Car","Bar","Smith","Doe","Ring"]

you can iterate over the first list and check against second list:

for (String column : ArrayList1) {
    boolean found = ArrayList2.stream().anyMatch(map.get(column)::equals);
    if (found){
        System.out.println(String.format("Found matching columns: %s -> %s.", column, map.get(column)));
    }
    else {
        System.out.println(String.format("No matching column found for: %s.", column));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM