不能将两个流组合起来在GUI中显示为一个流



我正在筛选游戏和控制台,但我想在GUI中同时显示它们,一次只显示其中一个流,两个流都按照我的意愿进行操作我只是找不到如何组合游戏和控制台的集合

//这两个流都在一系列具有主机、游戏、名称等的Rental中循环

//过滤出游戏名称

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

//过滤出控制台的名称

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

//根据客户的名称进行排序,这与正在显示的流一起工作

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

您可以在过滤器中使用OR来在结果中显示Game和Console,如下所示:

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

(在这种情况下,删除对filteredListRentals的第二个流和筛选器分配。(

您将两个流的结果分配给同一个变量,因此第二个流将取代第一个流。

如果你想要两个结果,你需要两个变量。然后,您可以将其中一个的结果附加到另一个。

逻辑可能类似于:

allRentals = (ArrayList<Rental>) listOfRentals.stream().filter(n -> n instanceof Game)...
consoleRentals = (ArrayList<Rental>) listOfRentals.stream().filter(n -> n instanceof Console)...
allRentals.addAll(consoleRentals);

感谢你们的帮助,这一切无疑让我朝着正确的方向去解决

fileredListRentals= (ArrayList<Rental>) listOfRentals.stream().
filter(n -> n instanceof Game)
.collect(Collectors.toList());
Collections.sort(fileredListRentals, (n1, n2) ->
n1.getNameOfRenter().compareTo(n2.nameOfRenter));
filteredConsoles = (ArrayList<Rental>) listOfRentals.stream().
filter(n -> n instanceof Console)
.collect(Collectors.toList());
Collections.sort(filteredConsoles,(n1,n2)->
n1.getNameOfRenter().compareTo(n2.nameOfRenter));
fileredListRentals.addAll(filteredConsoles);

最新更新