将列表中的元素映射到另一个列表中的位置

时间:2014-02-17 17:17:51

标签: java

想象一下,我们有两个列表,想要知道另一个列表中元素的位置。举例说明:

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

结果将是:

[-1, -1, 3]

因为B和I都不出现在第二个列表中,但是G出现在第三个位置。

这是我到目前为止所得到的:

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

是否有更快的解决方案可以避免List.indexOf()中的内部循环?

2 个答案:

答案 0 :(得分:4)

您可以使用Map

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

然后:

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

这样做,您可以直接获取索引,而不是每次查找和索引时都在可能非常大的列表上进行迭代。

答案 1 :(得分:2)

您可以使用HashMap<String, Integer>将每个角色映射到其位置。然后使用HashMap方法.containsKey()查找字段中是否存在某个字符串,.get()找出该位置。

HashMap<String, Integer> another;

for (String str : one) {

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