Advertisement
Guest User

Untitled

a guest
Jan 20th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. public static <T> Function<Supplier<T>, Optional<T>> firstNonNullMapper() {
  2. Map<Integer, Optional<T>> firstValueBox = new ConcurrentHashMap<>();
  3. firstValueBox.put(1, Optional.empty());
  4.  
  5. Set<Supplier<T>> footPrints = Collections.synchronizedSet(new HashSet<>());
  6.  
  7. return supplier -> {
  8. firstValueBox.merge(
  9. 1,
  10. Optional.empty(),
  11. (a, b) ->
  12. Stream.of(a, b)
  13. .filter(Optional::isPresent)
  14. .findFirst()
  15. .orElseGet(() -> {
  16. Optional<T> t = Optional.ofNullable(supplier.get());
  17. t.ifPresent(unused -> footPrints.add(supplier));
  18. return t;
  19. })
  20. );
  21.  
  22. return footPrints.contains(supplier) ? firstValueBox.get(1) : Optional.empty();
  23. };
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement