James
James

Reputation: 25

How to call methods on arrays within an ArrayList?

I've created an ArrayList called groupOfPeople by having a constructor that takes their name and ages. This was added to the ArrayList like this:

groupOfPeople.add(new Person(23,"Tom"));

Now I want to make that person call a sleep() method that is stored within another class. I've called it like this:

SleepClass callSleepClassr = new SleepClass();

Now I want to call the first person in the ArrayList and make them sleep so adding .callSleepClass.sleep() to them. The thing is, I don't know how to refer to that first array.

Any help is appreciated, thank you.

Upvotes: 0

Views: 91

Answers (3)

user1211
user1211

Reputation: 1515

You can call the function on each element on the list by doing:

for (Person  p : groupOfPeople) {
    p.callSleepClass.sleep();               
}

If you want to do it for the first element in the list, you can use:

if(groupOfPeople.size()>1)
    groupOfPeople.get(0).callSleepClass.sleep();

Upvotes: 0

If you want to put the first element in the list to sleep then get the element at index 0 in the list and invoke the method:

if(!groupOfPeople.isEmpty()){
    groupOfPeople.get(0).callSleepClass.sleep();
}

Upvotes: 0

Aimee Borda
Aimee Borda

Reputation: 842

By using Java8 streams, you can include the check for empty list as well,

groupOfPeople.stream().findFirst().ifPresent(SleepClass::sleep);

The sleep method should take a Person parameter then.

Upvotes: 1

Related Questions