Filter an object by specific properties java

So I have this class:

public class Seat {
    private Long id;
    private float positionX;
    private float positionY;
    private int numOfSeats;
    private String label;
    //getters and setters
}

I have List of Seat class on:

List<Seat> seatList = // get data from repository;

I also have this arraylist contains list of ids:

List<Long> idList; // for example : [1, 2, 3]

I want to filter seatList so that the filtered ArrayList does not contain a Seat object with id from idList, so I tried to use stream:

List<Seat> filteredSeat = seatList.stream()
   .filter(seat -> {
         // function to filter seat.getId() so it would return the Seat object with id that does not equals to ids from idList
   })
   .collect(Collectors.toList());

I cant find the correct function to do it. Does anyone have suggestion for me to try?

Upvotes: 0

Views: 578

Answers (3)

TacheDeChoco
TacheDeChoco

Reputation: 3913

Assuming you implement the equals method accordingly (like the doc mentions it), there is a much shorter solution:

seatList.stream()
   .distinct()
   .collect( Collectors.toList() );

Upvotes: 0

Brian Erlich
Brian Erlich

Reputation: 39

The most simple solution for be a for-each loop in which you check each idList against the Seat's id.

perhaps something like

List<Seat> FilteredList;
for ( Seat CurSeat : seatList ){
    for(int i = 0; i < idList.size(); i++){

and if the ID of CurSeat is part of idList, it doesn't get added to the new List. This is definitely not the simplest way, but if you're looking for something easy, this is probably it. Hope this helped!

Upvotes: 0

Nikolas
Nikolas

Reputation: 44378

You want to use the overriden method from Collection#contains(Object) with the negation implying the id was not found in the List.

Set<Seat> filteredSeat = seatList.stream()
    .filter(seat -> !idList.contains(seat.getId()))
    .collect(Collectors.toSet());

Few notes:

  • You want to use Set<Long> instead of List<Long> for an efficient look-up. Moreover, it doesn't make sense to have duplicate values among ids, so Set is a good choice.
  • Collectors.toSet() results Set, so the Stream's return type is Set<Seat>.

Upvotes: 2

Related Questions