【问题标题】:How to filter model object array list with another String arrays如何用另一个字符串数组过滤模型对象数组列表
【发布时间】:2017-08-13 18:13:41
【问题描述】:

如何用另一个字符串数组列表过滤模型对象数组列表

我的模型对象是

class City {
    String id;
    String cat_id;
    String city_id;
    String title_en;
}

我有城市对象列表List<City> events;

我想用另一个字符串数组过滤events

List<String> city_ids = {2,12,24,25};
List<String> cat_ids = {301,386,303,346};

我只想要在这些String 数组中具有city_idcat_idCity 对象。如何使用这些字符串列表过滤数组列表。

这是我的版本。我该如何改善这一点

List<City> filtered_events = new ArrayList<>();
    if (filtered_categories.size() > 0) {
            for (String c : filtered_categories) {

                for (City city: events) {
                    if (c.equalsIgnoreCase(city.getCat_id())) {
                        filtered_events.add(city);
                    }
                }
            }
        }

        if (filtered_cities.size() > 0) {
            for (String c : filtered_cities) {

                for (City city: events) {
                    if (c.equalsIgnoreCase(city.getCity_id())) {
                        filtered_events.add(city);
                    }
                }
            }
        }

【问题讨论】:

    标签: java android arraylist


    【解决方案1】:

    有很多方法。一种使用 java 流的方法:

    List<City> filteredCities = events.stream()
        .filter(c -> city_ids.contains(c.city_id) && cat_ids.contains(c.cat_id))
        .collect(Collectors.toList()):
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 2020-01-27
      • 2018-10-03
      • 2021-05-14
      • 1970-01-01
      相关资源
      最近更新 更多