Skip to content

Instantly share code, notes, and snippets.

@pax95
Created November 11, 2017 21:54
Show Gist options
  • Save pax95/8e118dddf12d70fd81ea77b503367386 to your computer and use it in GitHub Desktop.
Save pax95/8e118dddf12d70fd81ea77b503367386 to your computer and use it in GitHub Desktop.
package test;
import static java.time.temporal.ChronoUnit.MILLIS;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
public class Test {
public static void main(String[] args) {
System.out.println(new Test().getClosest("123", LocalDateTime.now()
.plusMinutes(0)));
}
private Optional<Dummy> getClosest(String id, LocalDateTime time) {
List<Dummy> list = List.of(new Dummy(LocalDateTime.now(), "123", "1"),
new Dummy(LocalDateTime.now()
.plusMinutes(4), "123", "2"),
new Dummy(LocalDateTime.now()
.plusMinutes(42), "123", "22"));
return list.stream()
.filter(dummy -> dummy.id.equals(id))
.reduce((result, current) -> Math.abs(MILLIS.between(time, current.getTime())) < Math.abs(MILLIS.between(time, result.getTime())) ? current : result);
}
public static class Dummy {
final LocalDateTime time;
final String id;
final String title;
public Dummy(LocalDateTime time, String id, String title) {
this.time = time;
this.id = id;
this.title = title;
}
public LocalDateTime getTime() {
return time;
}
public String getId() {
return id;
}
@Override
public String toString() {
return time.toString() + " " + title;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment