为子集的每个元素获取set的索引

时间:2014-07-02 19:15:01

标签: java collections

假设我有:

String[] superArray = new String[] { "a", "b", "c", "d", "e"};
String[] subArray = new String[] { "b", "e"};

问题: superArray的每个元素在subArray中获取索引的优雅方法是什么?

例如,我希望得到[1, 4]结果。

更新:[第二(相关)问题]

如何通过索引复制数组?示例

String[] array = new String[] { "a", "b", "c", "d", "e"};
Integer[] indexes = new Integer[] { 1, 4 };
copyArrayByIndexes(array, indexes); // returns {"b", "e"}

2 个答案:

答案 0 :(得分:4)

您可以使用已订购的列表

List<String> superSet = Arrays.asList("a,b,c,d,e".split(","));
List<String> subSet = Arrays.asList("b", "e");
superSet.containsAll(subSet);
List<Integer> indexes = subSet.stream().forEach(superSet::indexOf)
                                       .collect(Collectors.toList()); 

String[] array = { "a", "b", "c", "d", "e"};
int[] indexes = new int[] { 1, 4 };
List<String> lookup = Arrays.stream(indexes).forEach(i -> array[i])
                                            .collect(Collectors.toList());

答案 1 :(得分:1)

你应该帮自己一个忙,并使用列表而不是数组。您可以使用java.utils.Arrays轻松地将一个转换为另一个。列表中只有更多辅助方法,正确实现了equals方法,可以根据需要增长等。

使用Lists,您可以实现以下两个功能:

public static <T> List<Integer> getIndices(List<T> list, List<T> sublist) {
    List<Integer> result = new ArrayList<Integer>();
    for (T t : sublist) {
        result.add(list.indexOf(t));
    }
    return result;
}

public static <T> List<T> copyByIndices(List<T> list, List<Integer> indices) {
    List<T> result = new ArrayList<T>();
    for (Integer i : indices) {
        result.add(list.get(i));
    }
    return result;
}

用法:

List<String> superArray = Arrays.asList("a", "b", "c", "d", "e");
List<String> subArray = Arrays.asList("b", "e");       
List<Integer> indices = getIndices(superArray, subArray);
List<String> copy = copyByIndices(superArray, indices);
System.out.println(indices);                 // -> [1, 4]
System.out.println(copy);                    // -> [b, e]
System.out.println(subArray.equals(copy));   // -> true
相关问题