0

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.

2
  • iterate and call on each element OR use java8 forEach Commented Dec 3, 2016 at 7:51
  • for (Person x : people) { x.callshower.shower(); } doesn't work, how would I make x do this? Commented Dec 3, 2016 at 8:00

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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();
}

Comments

0

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();

1 Comment

this is not correct, op defined groupOfPeople as an ArrayList, not an Array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.