简体   繁体   中英

Comparing two ArrayLists of Objects

I have class named Student. Also I have two array lists for Students A and Students B.

Students A could be: Maria, Alex, Lora, Vlad, Lauren, Catherine.

Students B is some students from A: Maria, Alex

Students A has the proper id and names stored. But Students B has only prepared names and hardcoded id stored.

I separated these two lists and now want do the following:

if Maria form Array A has student id : 2427

Maria from Array B should receive the same student id.

Can you please help me to do that.

 //array lists of students a and b
public void common(){

     ArrayList<ArrayList<Student>> lists = new ArrayList<ArrayList<Student>>();
     lists.add(a);
     lists.add(b);

     System.out.println(getCommonElements(lists));
     for (int i = 0; i < lists.size(); i++) {
         aa = lists.get(0);
         bb = lists.get(1);

     }
     System.out.println(aa);
     System.out.println(bb);
}


public static <T> Set<T> getCommonElements(Collection<? extends Collection<T>> collections) {

    Set<T> common = new LinkedHashSet<T>();
    if (!collections.isEmpty()) {
       Iterator<? extends Collection<T>> iterator = collections.iterator();
       common.addAll(iterator.next());
       while (iterator.hasNext()) {
          common.retainAll(iterator.next());
       }
    }
    return common;
}

Thank you in advance! the question is rarely why this do not work?

for (int i = 0; i < a.size(); i++) {
  for (int j = 0; j < b.size(); j++) {

      if(a.get(i).getName().equals(b.get(j).getName())){
                //does not go there at all
   }
  }
 }

Your iteration is not doing what you meant it to do. You are comparing elements at index 'i' in both arrays over and over, instead of elements in A at index 'i' and elements in B at index 'j'.

If you print out the name of each student that you comparing it should be clear to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM