Java List fitering

时间:2018-03-28 10:38:25

标签: java android

我是Java的新手,我创建了一个像

这样的列表
List<TruckCategoriesModel> catvals = truckcatesq.getLocationTruckCategories("tryone"));

我的TruckCategoriesModel包含

private String category,header_loc;
private int db_id;
//getters and setters for the above

现在经过一些计算后,我有几个代表类别的索引。我有一个列表,其中包含一个列表,例如

fruit, juice, mango

我得到了

private List<String> truckcategories = new ArrayList<String>();
for (int j=0; j<catvals.size(); j++){
      truckcategories.add(catvals.get(j).getCategory());
}

所以在点击上面的列表(truckcategories)后,设置了特定列表项的索引的另一个整数,所以

fruit  //gets 0
, juice //gets 1

所以我的整数是

Integer[] selecteditems = [0,1....]//the selected items

所以,现在我想知道如何根据List<TruckCategoriesModel> catvals = truckcatesq.getLocationTruckCategories("tryoone"));索引过滤旧的selecteditems

2 个答案:

答案 0 :(得分:3)

鉴于以下原始清单:

List<TruckCategoriesModel> catvals = new ArrayList<>();
catvals.add(new TruckCategoriesModel("fruit", "s1", 1));
catvals.add(new TruckCategoriesModel("juice", "s2", 2));
catvals.add(new TruckCategoriesModel("mango", "s3", 3));

你循环应生成以下truckcategories

[fruit, juice, mango]

然后现在,如果你想过滤1(juice

int filterIndex = 1; // juice

// lookup the corresponding category string
String filterCategory = truckcategories.get(filterIndex);

// filter
List<TruckCategoriesModel> filteredList = new ArrayList<>();
for(TruckCategoriesModel tcm : catvals) {
  if(filterCategory.equals(tcm.getCategory())) {
    filteredList.add(tcm);
  }
}

答案 1 :(得分:1)

如果你有 minSdkVersion&gt; = 24 和Java 8支持,那么你可以使用Java 8流:

List<TruckCategoriesModel> filteredList = catvals.stream()
                        .filter(item -> filterCategory.equals(item.getCategory()))
                        .collect(Collectors.toList());

或者如果你正在使用RxJava2库:

List<TruckCategoriesModel> filteredList = Observable.fromIterable(catvals)
                .filter(item -> filterCategory.equals(item.getCategory()))
                .toList()
                .blockingGet();

这些是一些先进的方法,但值得检查。