pixel
pixel

Reputation: 26533

Find closest object in Java collection

I have a collection with objects that contain certain int field.

eg.

public class Foo {
    public int field;
}

I would like to get an element that has closest value to certain value (eg. 42).

Is there any neat method from guava to achieve such thing?

Upvotes: 4

Views: 3864

Answers (3)

Aaron
Aaron

Reputation: 24822

In pure java, you could reduce the collection to its element with the lesser difference to your goal :

myFoos.stream()
      .reduce((result, current) -> 
              Math.abs(42 - current.field) < Math.abs(42 - result.field) ? current : result);

Upvotes: 5

Andy Turner
Andy Turner

Reputation: 140564

If you specifically want to use Guava, you can use an Ordering:

final int target = 42;
Ordering<Foo> ordering = Ordering.natural().onResultOf(
    new Function<Foo, Integer>() {
      @Override public Integer apply(Foo foo) {
        return Math.abs(foo.field - target);
      }
    });

Now you can simply find the minimum value according to this ordering:

Foo closest = ordering.min(iterableOfFoos);

However, you can do this with streams in Java 8, as suggested by @wero.

Upvotes: 6

wero
wero

Reputation: 33010

(Not Guava but Java streams): Use Stream.min and a custom comparator:

 List<Foo> list = ...
 Foo closest42 = list.stream()
      .min((f1,f2) -> Math.abs(f1.field - 42) - Math.abs(f2.field - 42)));

Upvotes: 11

Related Questions