Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 944
pixel Avatar asked Nov 28 '22 23:11

pixel


2 Answers

(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)));
like image 151
wero Avatar answered Dec 04 '22 13:12

wero


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.

like image 29
Andy Turner Avatar answered Dec 04 '22 13:12

Andy Turner