我有两个Array
,如下所示:
String a[]={"book","pen"};
String b[]={"pen","pencil","bottle","book","bag"};
我想检查array b
和array a
之间的相同值,我试过这个:
for (int i=0; i < b.length; i++){
for (int j=0; j < a.length(); j++){
if(!(a.contains(b[i]))){
//delete if not same
}
所以我的问题,如何在两个arraylist android之间检查相同的值?
答案 0 :(得分:4)
试试这个..
for (int i=0; i < b.length; i++){
for (int j=0; j < a.length(); j++){
if(!(a[j].equals(b[i]))){
//do something for not equals
}else{
//do something for equals
}
}
}
或者
ArrayList<String> A_arraylist = new ArrayList<String>(Arrays.asList(a));
ArrayList<String> B_arraylist = new ArrayList<String>(Arrays.asList(b));
for (int i=0; i < A_arraylist.size(); i++){
if(B_arraylist.contains(A_arraylist.get(i))){
//do something for equals
}else{
//do something for not equals
int index = B_arraylist.indexOf(A_arraylist.get(i));
B_arraylist.remove(index);
}
}
修改强>
B_arraylist.retainAll(A_arraylist);
答案 1 :(得分:2)
你可以这样做。在String API
中使用.equals()
方法
for (int i=0; i < b.length; i++){
for (int j=0; j < a.length; j++){
if(a[j].equals(b[i])){
// a[j] matches b[i]. Perform operation when they are equal
}else{
// it doesn't match
}
}
}
答案 2 :(得分:1)
试试这个。我将它用于int数组,你可以修改它为字符串
int[] arr1 = {4,7,3,9,2};
int[] arr2 = {3,2,12,9,40,32,4};
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i]==arr2[j]){
System.out.println(arr1[i]);
}
}
}
或者,如果您使用ArrayList,请尝试以下
public static void main(String[] args) {
List<String> list_One = new ArrayList<String>();
List<String> list_two = new ArrayList<String>();
list_One.add("A");
list_One.add("B");
list_One.add("C");
list_One.add("D");
list_two.add("E");
list_two.add("F");
list_two.add("C");
list_two.add("D");
System.out.println("is list_two Containts List_one Elements ?");
Iterator<String> itr =list_two.iterator();
while(itr.hasNext()){
String list_two_element = itr.next();
if(list_One.contains(list_two_element)){
System.out.println("Matching Element found in list two : " + list_two_element);
}
}
}
希望这会对你有所帮助。谢谢
答案 3 :(得分:1)
您可以尝试使用Collections
现在重命名为Guava
从here
获取jar文件由于数组列表的长度不同,您可以做的是:
1.获取具有最大尺寸的阵列的长度
int sizeOfArrayOne = array.length;
int sizeOfArrayTwo = array2.length;
比较尺寸
2.一旦你获得哪个数组是最大的,你就可以使用Guava为你找到另一个数组的值,如:
String value = Iterables.find(arrayWithLargerSize, new SearchForString(arrayOfSmallerSize[i]),null);
if(value == null) {
// the string is not present in the array
}else {
// the string is present in the array
}
在较小数组的循环内运行此块( i 表示循环的i)。
3.编写搜索谓词类,如下所示:
class SearchForString implements Predicate<String> {
// override the methods here
// also ensure that you implement the correct predicate
// one that belongs to the guava collection
}
希望这个线索足够!
答案 4 :(得分:1)
String a[]={"book","pen"};
String b[]={"pen","pencil","bottle","book","bag"};
for(int i=0;i<b.lenght;i++){
String firstValue=b[i];
for(int j=0;j<a.lenght;j++){
String secondValue=a[j];
if(firstValue.equalsIgnoreCase(secondValue)){
// item matches;
}
}
}