简体   繁体   中英

How do I make a loop that would find each distinct number inside an ArrayList in java?

I have a java class called StudentList and I want to make a method which would go through each student and check their group numbers. Then add them to an arraylist, if the group number is already inside the arraylist then it would skip it. But how do I make a loop that would skip duplicates?

I've tried using the for loop but I can't think of a solution past this one point:

public ArrayList<Integer> getAllGroupNumbers() {
    ArrayList<Integer> a = new ArrayList<Integer>();
    for(int i = 0; i < list.size(); i++)
    {
        if(list.get(i).getGroupNumber() != ...)
    }
}

You can use.contains method in ArrayList to check if an element is already present in the list. Sample code would be like the one follows.

for(int i = 0; i < list.size(); i++)
{
  Integer groupNumber = list.get(i).getGroupNumber();
  if( !a.contains(groupNumber) ) {
     a.add(groupNumber);
  }
}

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