【问题标题】:Return specific object from an ArrayList从 ArrayList 返回特定对象
【发布时间】:2019-03-13 21:51:20
【问题描述】:

我有一个 ArrayList,其中包含数千个带有许多变量(包括城市)的属性。我只需要访问/返回特定城市的房产,例如萨里的所有房产。我如何得到它们?

我知道如何通过 city.values("Surrey") 搜索它们。但我不知道如何输出这些值。

【问题讨论】:

  • 到目前为止你尝试过什么?为了与正确的问题标准兼容,此问题缺少很多内容。
  • 我什么都没试过,我的数组列表中有属性,其中包含城市、价格、所有者等变量,我需要搜索数组列表并仅输出 surrey 中的属性。抱歉,由于我是 java 新手,所以我在解释这一点和使用正确的术语方面真的很糟糕。
  • 你能展示你的 ArrayList 还是它的一部分?
  • 我已经编辑了我的帖子
  • “我什么都没试过,”...没有人会为你做功课。如果您尝试过某事..请启发我们,我们将成为您寻求解决所述问题的参与者..

标签: java arrays arraylist


【解决方案1】:

我假设您想在您的 AirbnbListing 列表中进行搜索。您可以使用Java Stream。为此使用filter 方法:

List<AirbnbListing> matchingListings = listings.stream()
    .filter(l -> "Surrey".equals(l.getCity()))
    .collect(Collectors.toList());

如果你想要一个所有城市的列表,你可以使用map方法:

List<String> matchingListings = listings.stream()
    .map(l -> l.getCity())
    .collect(Collectors.toList());

另外here是官方的Java流解释教程。

【讨论】:

  • List matchingListings = Listings.stream().filter(l -> neighbourhood.equals("London")).collect(Collectors.toList());这也有效吗?
  • neighbourhood 变量是什么?
【解决方案2】:

如果您使用的是 Java 8 或更高版本,则有以下选项: list.stream().filter(x -&gt; "Berlin".equals(x.getCity())); //This filters the list and returns a list with city = Berlin.

希望这是您正在寻找的。

【讨论】:

    猜你喜欢
    • 2014-04-03
    • 1970-01-01
    • 2015-11-15
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    • 2022-01-01
    • 2018-08-04
    相关资源
    最近更新 更多