简体   繁体   中英

Map elements in a list to positions in another list

Imagine we have two lists and want to know the postions of elements from one list in the other. To illustrate:

List<String> one = Arrays.asList("B", "I", "G");
List<String> another = Arrays.asList("L", "A", "R", "G", "E");

Result would be:

[-1, -1, 3]

because neither B nor I occur in second list, but G does on 3rd position.

This is what I came with so far:

<E> List<Integer> indices(List<E> elements, List<E> container) {
    List<Integer> indices = new ArrayList<>(elements.size());
    for (int i = 0; i < elements.size(); i++) {
        indices.add(container.indexOf(indices.get(i)));
    }
    return indices;
}

Is there a faster solution that avoids internal loop in List.indexOf() ?

You can use Map :

Map<String, Integer> otherMap = new HashMap<>(other.size());
int index = 0;
for(String otherElem : other) {
    otherMap.put(otherElem, index++);
}

And then:

for(String oneElem : one) {
    Integer index = otherMap.get(oneElem);
    indices.add(index == null ? -1 : index);
}

Doing so, you get the index directly instead of iterating on a potentially very big list each time you look for and index.

You can use a HashMap<String, Integer> that would map every character to its position. Then use HashMap method .containsKey() to find out, if a certain String is present in the field and .get() to find out the position.

HashMap<String, Integer> another;

for (String str : one) {

    if (another.contains(str)) {
        result.add(another.get(str));
    } else {
        result.add(-1);
    }
}

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