![](/img/trans.png)
[英]How to compare the elements of an ArrayList with every element of another ArrayList using Stream API of Java 8?
[英]How to compare elements in an array list using the index provided by another arraylist
我有一個ArrayList: A
包含索引array
,類似於[[0,1],[4,5,6]]
。 這份名單是動態的,基於我有2周整數一些前期操作,我做的規模可能會增長arraylists
大小相等的說7
。 像這樣: B: [1,1,4,5,2,3,2]
和C: [3,3,4,5,6,6,6]
我需要幫助來比較由arrayList: A
in B
和C
表示的索引處的元素
例子:
比較 arrayList B 中索引[0,1]
處的元素並檢查list.get[0] == list.get[1]
和[4,5,6]
檢查是否list.get[4] == list.get[5] == list.get[6]
array list C
相同
非常感謝任何幫助。 提前致謝
正如您所說,使用 arraylist A
的值作為其他列表的索引:
示例A = [0,1] , B[3, 3]
您需要檢查是否:
B[0] == B[1]
但是將索引重寫為A
值,您會得到:
B[A[0]] == B[A[1]]
只需將其擴展到一般情況即可解決問題。
static boolean checkIndex ( List<List<Integer>> indexList, List<Integer> listToCheck ){
for (List<Integer> indices : indexList) {
int val = listToCheck.get( indices.get(0) );
for (int i = 1; i < indices.size(); i++) {
int index = indices.get(i);
if ( listToCheck.get(index) != val ) {
return false;
}
}
}
return true;
}
我會循環所有索引列表並檢查另一個列表中相應索引的所有值。
測試
public static void main(String[] args) {
List<List<Integer>> indexList = new ArrayList<>();
indexList.add(Arrays.asList(0,1));
indexList.add(Arrays.asList(4,5,6));
System.out.println(indexList);
List<Integer> tempList = Arrays.asList(1,1,4,5,2,3,2);
List<Integer> tempList2 = Arrays.asList(3,3,4,5,6,6,6);
System.out.println(tempList);
System.out.println(checkIndex( indexList, tempList));
System.out.println(tempList2);
System.out.println(checkIndex( indexList, tempList2));
}
//輸出
[[0, 1], [4, 5, 6]]
[1, 1, 4, 5, 2, 3, 2]
false
[3, 3, 4, 5, 6, 6, 6]
true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.