我有两个ArrayList
,其中存储了字符串值。
列表可以是:不同大小,每个列表具有相同的值以及不同的不匹配字符串。
示例:
List 1: "a","b","b","c","e","a","e","f","g";
List 2: "a","a","b","c","a","e","a","d","f","e","e","g";
我想要得到的结果是与列表2相比按列表1的顺序匹配的值。因此,该示例的结果将是:
结果:
[String] [pos L1] [pos L2]
["a"] [0] [0]
["b"] [1] [2]
["c"] [3] [3]
["e"] [4] [5]
["a"] [5] [6]
["e"] [6] [9]
["g"] [8] [11]
答案 0 :(得分:1)
执行两个嵌套循环,并从在内部循环的上一次迭代中停止的索引开始在第二个循环中进行迭代:
// valid TS code:
var obj = {
foo: 123,
valueOf: function(){return this.foo;}
};
console.log((obj as any) + 1); //will be 124
// workaround - using '+' sign (valueOf used as well)
console.log(+obj + 1); //will be 124
用于测试:
public static List<String> algo(List<String> l1, List<String> l2) {
List<String> result = new ArrayList<>();
int lastIndexFound = 0;
for(int i = 0; i < l1.size(); i++) {
for(int j = lastIndexFound; j < l2.size(); j++) {
String list1element = l1.get(i);
String list2element = l2.get(j);
if(list1element.equals(list2element)) {
result.add(list1element);
lastIndexFound = j + 1;
break;
}
}
}
return result;
}
这将输出:
List<String> list = Lists.newArrayList("a","b","b","c","e","a","e","f","g");
List<String> list2 = Lists.newArrayList("a","a","b","c","a","e","a","d","f","e","e","g");
algo(list, list2).forEach(System.out::println);
答案 1 :(得分:-1)
ArrayList<yourElementType> resultsArray = new Arraylist<yourElementType>()
for (yourElementType e : List1){
if(List2.contains(e)){
resultsArray.add(e)
// if you want the exact position, use list2.indexof(e)
}
}