Java List fitering Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Java List fitering without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m new to Java and I have created a list like

List<TruckCategoriesModel> catvals = truckcatesq.getLocationTruckCategories("tryone"));

My TruckCategoriesModel contains

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

Now after some calculations I have several indexes with represent category. I have a list in which contains a list e.g.

fruit, juice, mango

Which I got by

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

So after clicking on the above list(truckcategories) am setting up another integers of indexes of the specific list item so

fruit  //gets 0
, juice //gets 1

So my integers i have are

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

So, now I want to know how to filter the old List<TruckCategoriesModel> catvals = truckcatesq.getLocationTruckCategories("tryoone")); per the selecteditems indexes.

Answer

Given the following original list:

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));

you loop should generate the following truckcategories:

[fruit, juice, mango]

Then now if you want to filter on 1 (which is 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);
  }
}
We are here to answer your question about Java List fitering - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji