Get the two min objects from a set using Java stream

You can get the second min value as follows:

 set.stream()
    .filter(s -> s.getValue() != minObject.getValue())     
    .min(Comparator.comparingInt(object -> object.getValue()))
    .get();
  • This streams over the set of elements again ensuring that we're ignoring the previous min value via filter.
  • Then we get the min value via min

or you can get both at the same time:

Stream<SomeObject> twoMinValues = set.stream()
                   .sorted(Comparator.comparingInt(object -> object.getValue()))
                   .limit(2);
  • This streams over the set of elements, sorting the entire sequence from smallest to largest and then taking the first two which is definitely less efficient than the above approach due to the behaviour of the "sorted" intermediate operation.

The awnser should be fast because In my real program i call this method many times and my Sets are very Large.

As for needing a "fast" program, I'd recommend that you first try to solve the problem at hand just using the typical imperative approach as in most cases they're faster than using streams.

if it's not much better then "consider" using parallel streams if and only if you know that you can leverage parallelism.

see Should I always use a parallel stream when possible?


You can pass your Set<E> to an instance of NavigableSet<E>, then you can poll the first two (lowest) elements from it :

final NavigableSet<SomeObject> navigableSet = new TreeSet<>(Comparator.comparingInt(SomeObject::getValue));

navigableSet.addAll(set);

final SomeObject firstMin = navigableSet.pollFirst();

final SomeObject secondMin = navigableSet.pollFirst();