Search code examples
javaarraylistsortedlist

Filter Java List by two unique attributes


Please I'm trying to filter a list which I queried from the DB by two unique attributes. Here is a sample of the table:

id | seatNo | time | type
=== ======== ====== =====
1  |   1    |   1  |  1  *
2  |   2    |   1  |  1
3  |   1    |   2  |  1  *
4  |   2    |   2  |  1
5  |   3    |   1  |  2  *
6  |   4    |   1  |  2

The lines with asterisk(*) are the unique values for both time and type. How do i write a loop that filters this list for unique objects by both the time and type. I have tried something like this:

int currentTime = 0;
int currentType = 0;
List<Bus> sortedBuses = new ArrayList<>();
for (Bus bus : allSeats) {
    if (bus.getTime()!= currentTime && bus.getType != currentType) {
        sortedBuses.add(bus);
    }
    currentId = bus.getTime();
    currentType = bus.getType();
}

But this doesn't filter properly. I can only get unique values like where time & type are equal. Any ideas that could help me solve this are welcome.


Solution

  • You will have to filter against the busses which are stored in sortedBuses

    List<Bus> sortedBuses = new ArrayList<Bus>();
    
    outerloop:
    for (Bus bus : allSeats) {
       for (Bus sorted : sortedBuses)
          if (bus.getTime()==sorted.getTime() && bus.getType == sorted.getType)
            continue outerloop;
       sortedBuses.add(bus);
    }