简体   繁体   中英

Compare string with arraylist element and get another arraylist element

public ArrayList<String> endDuration(String searchedKey, ArrayList<ArrayList<String>> keys, ArrayList<ArrayList<String>> values) {
    for (int i = 0; i < keys.size() && i < values.size(); i++) {
        if (searchedKey.equals(keys.get(i))) {
            return values.get(i);
        }
    }
    return null;
}

I am having two lists both are string lists. Also I am having one string.

I want to compare the string with first list of all strings if any of the list values matches with string. I want to get string value from second list in that position.

Eample:

ArrayList<String> strvalue = (a,b,c,d,e)
ArrayList<String> intValues = (1,2,3,4.5)
String str=c;

I want to get integer value 3.

Pretty Simple stuff. You can use the following code:

public static List<String> endDuration(String searchedKey, List<List<String>> keys, List<List<String>> values) {
    Iterator<List<String>> itKey = keys.iterator();
    Iterator<List<String>> itValue = values.iterator();
    Set<String> uniqueKeys = new HashSet<>();

    while (itKey.hasNext() && itValue.hasNext()) {
        List<String> v = itValue.next();
        uniqueKeys.clear();
        uniqueKeys.addAll(itKey.next());

        if (uniqueKeys.contains(searchedKey))
            return v;
    }

    return Collections.emptyList();
}

Pretty Simple stuff. You can use the following code:

public int getSecondListValue(ArrayList<String> list1, ArrayList<Integer> list2, String compare) {

    for (int i = 0; i < list1.size() && i < list2.size(); i++) {
        if (list1.get(i).equals(compare)) 
            return list2.get(i);
    }
    return null;
}

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