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?
(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)));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With