-3

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<person> people = new ArrayList<person>();

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?

5
  • 1
    Show us how you would do that with a for loop. Iterator approach is almost the same. Commented Oct 15, 2020 at 9:50
  • 1
    You can do exactly the same thing as you would do with strings. The only different thing would be the interior of the loop, where insted of string comparison you should compare the name of the person instead. Commented Oct 15, 2020 at 9:52
  • Java conventions usually have class name uppercased and camelCase for variables. Also you don't need a semicolon at the end of the class. The arraylist statement could be simplified for ArrayList<person> people = new ArrayList<>; To iterate, do for (person certainPerson : people) { if (certainPerson.name == "Fred") { //do whatever } } Commented Oct 15, 2020 at 9:57
  • Questions looking for tutorials are off-topic, sorry Commented Oct 15, 2020 at 10:05
  • Using the for-each-loop, you lose the actual iterator. If you want the index, you need to use an explicit iterator. Commented Oct 15, 2020 at 10:29

1 Answer 1

1

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

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)) { // 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<Person> list, String name) {
  return list.stream().filter(p -> name.equals(p.getName())).findFirst().orElse(null);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.