Search code examples
javaarraysfiltercollectionsjava-stream

Combine two streams to display as one in GUI


I am filtering out games and consoles but then I want to display them both in a GUI, only one of the streams will display at a time, both streams do what I want them to I just can't find out how to combine a collection of games and consoles.

//both streams cycle through an array of Rentals that have the consoles, games, names, etc

//filters out the name of games

        filteredListRentals = (ArrayList<Rental>) listOfRentals.stream().
                        filter(n -> n instanceof Game)
                        .collect(Collectors.toList());

//filters out the name of the consoles

        filteredListRentals = (ArrayList<Rental>) listOfRentals.stream().
                        filter(n -> n instanceof Console)
                        .collect(Collectors.toList());


//sorts by the name of costumers, this works along with the stream being displayed

       Collections.sort(fileredListRentals, (n1, n2) ->
              n1.getNameOfRenter().compareTo(n2.nameOfRenter));

Solution

  • You can use OR inside your filter to have Game and Console in the result, like this:

    filteredListRentals = (ArrayList<Rental>) listOfRentals.stream()
        .filter(n -> n instanceof Game || n instanceof Console)
        .sorted((n1, n2) -> n1.getNameOfRenter().compareTo(n2.nameOfRenter))
        .collect(Collectors.toList());
    

    (Remove in this case the second stream & filter assignment to filteredListRentals.)