2

I have list of objects objList which has two fields age and id. age is long and id is String. I want to iterate over the list and get the id of object that has minimum age in the list. I can do it with a traditional for loop, but I am sure there would be a compact solution in java 8.

If I do objList.stream() and then check map functions on that stream, I just have mapToInt, mapToLong, and mapToDouble. With these I get the min age, but I need id of the object that has minimum age.

Its guaranteed that the list will not be empty and will have at least one object.

5
  • What if the list is empty? Commented Jun 23, 2017 at 0:25
  • Ohh in my case its guaranteed that the list will not be empty. Will add that in the description. Commented Jun 23, 2017 at 0:26
  • 2
    Why would age be long? Commented Jun 23, 2017 at 0:31
  • 1
    @shmosel Could be the raw value of a Date, for example. Commented Jun 23, 2017 at 0:33
  • @shmosel yes. It will be represented as unix timestamp. Commented Jun 23, 2017 at 0:38

2 Answers 2

5

Assuming the elements in the list are of type MyObject, and offer accessors getAge() and getId(), the pipeline would look like this:

String id = objList.stream()
  .min(Comparator.comparingLong(MyObject::getAge))
  .map(MyObject::getId)
  .orElseThrow(IllegalArgumentException::new);

If your assumption is invalid, and objList is empty, this will throw an IllegalArgumentException—but that will "never happen," right? Alternatively, you could return a default value or generate one.

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

Comments

3
objList.stream()
        .min(Comparator.comparingLong(MyObj::getAge))
        .orElseThrow(AssertionError::new)
        .getId()

2 Comments

The min function returns Optional<T> right? So in this case it would return Optional<MyObj>. The optional will be empty if the list is empty.
Or without streams: Collections.min(objList, Comparator.comparingLong(MyObj::getAge)) .getId()

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.