Java在包含类的ArrayList中使用迭代器查找项目

huangapple go评论77阅读模式
英文:

Java finding item in ArrayList of classes with an Iterator

问题

我找不到关于这个的教程,每个教程似乎都使用了一个字符串的ArrayList。

假设你有一个名为Person的类,其中包括很多属性,包括名字。

class Person
{
    public String name;
    public int age;
    public int weight;
    public String hair_colour;
    public String eye_colour;
};

你有一个Person的ArrayList,你想要在这个ArrayList中找到一个人,你只有他们的名字。

ArrayList<Person> people = new ArrayList<Person>();

我如何找到“Fred”?

我知道可以循环遍历列表中的所有项,但我想要用迭代器来正确地做这个。

有人知道有没有教程来解释如何使用迭代器在ArrayList中进行查找,只使用该项的一个属性来查找项目?

或者这不可能吗?我对迭代器有误解吗?

英文:

I can't find a tutorial of this, every tutorial seems to use an ArrayList of strings.

Suppose you have a class Person which has many attributes including name.

class person
{
    public String name;
    public int age;
    public int weight;
    public String hair_colour;
    public String eye_colour;
 };

You have a ArrayList of persons and you want to find one person in this ArrayList and you only have their name.

ArrayList&lt;person&gt; people = new ArrayList&lt;person&gt;();

How do I find "Fred"?

I know it's possible to loop though all the items in list but I want to do this properly with an Iterator.

Does anyone know of a tutorial to explain how to do a find on an ArrayList using an Iterator to find an item using just one attribute of that item?

Or is this just not possible? Have I misunderstood Iterator's?

答案1

得分: 1

正如评论中指出的那样,迭代器方法与您在标准循环中所做的非常相似:

public static Person findPersonByName(List<Person> list, String name) {
    Iterator<Person> it = list.iterator();
    while (it.hasNext()) {
      Person p = it.next();
      if (p.getName().equals(name)) { // 找到人,返回对象
        return p;
      }
    }
    return null; // 未找到返回 NULL
}

如果您使用的是 Java 8 或更高版本,也许可以尝试使用流(streams),它们可以使代码变得更加简洁:

public static Person findPersonByName(List<Person> list, String name) {
  return list.stream().filter(p -> name.equals(p.getName())).findFirst().orElse(null);
}
英文:

As pointed out in comments, iterator approach is very similar to what you do with standard loops:

public static Person findPersonByName(List&lt;Person&gt; list, String name) {
    Iterator&lt;Person&gt; it = list.iterator();
    while (it.hasNext()) {
      Person p = it.next();
      if (p.getName().equals(name)) { // Person found, return object
        return p;
      }
    }
    return null; // Not found return NULL
}

If you're using Java 8 and above, maybe you can try out streams(), they make this very compact:

public static Person findPersonByName(List&lt;Person&gt; list, String name) {
  return list.stream().filter(p -&gt; name.equals(p.getName())).findFirst().orElse(null);
}

huangapple
  • 本文由 发表于 2020年10月15日 17:46:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64368919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定