Skip to content

Instantly share code, notes, and snippets.

View pellse's full-sized avatar

Sebastien Pelletier pellse

View GitHub Profile
@FunctionalInterface
public interface CheckedFunction<T, R> {
R apply(T t) throws Exception;
}
public static <T, R> Function<T, R> unchecked(CheckedFunction<T, R> checkedFunction) {
return t -> {
try {
return checkedFunction.apply(t);
} catch (Exception e) {
List<Customer> customers = Stream.of(1L, 2L)
.map(id -> {
try {
return queryDatabaseForCustomer(id);
} catch (SQLException e) {
throw new RuntimeException(e); // or custom subclass of RuntimeException
}
})
.collect(toList());
private Customer queryDatabaseForCustomer(Long id) throws SQLException {
// issue a database call and return the corresponding Customer
}
List<Customer> entities = Stream.of(1L, 2L)
.map(this::queryDatabaseForCustomer) // Doesn't compile
.collect(toList());
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
List<Integer> numbers = Stream.of("1", "2")
.map(Integer::parseInt)
.collect(toList());
@Test
public void testOrderList() {
List<Item> items = Stream.of(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L)
.map(Item::new)
.collect(toList());
List<Item> reorderedList = Lists.orderList(items, asList(5L, 3L, 6L, 1L), Item::getId);
List<Long> reorderedIds = reorderedList.stream()
.map(Item::getId)
public static <E, T> List<E> orderList(List<E> listToReorder, Collection<? extends T> newOrder, Function<? super E, ? extends T> mapper) {
return reorderCollection(listToReorder, newOrder, mapper, ArrayList::new);
}
public static <E, T> Set<E> orderSet(Set<E> setToReorder, Collection<? extends T> newOrder, Function<? super E, ? extends T> mapper) {
return reorderCollection(setToReorder, newOrder, mapper, HashSet::new);
}
Set<Item> setToReorder = getSetToReorder();
List<Long> newOrder = getNewOrder();
Set<Item> reorderedSet = reorderCollection(setToReorder, newOrder, Item::getId, HashSet::new);
public static <E, T, C extends Collection<E>> C reorderCollection(C collectionToReorder,
Collection<? extends T> newOrder,
Function<? super E, ? extends T> mapper,
Supplier<? extends C> collectionSupplier) {
if (Stream.of(newOrder, collectionToReorder).anyMatch(Collections::isEmpty)) {
return emptyIfNull(collectionToReorder, collectionSupplier);
}
Map<T, E> collectionItemMap = collectionToReorder.stream()
Set<Item> setToReorder = getSetToReorder();
List<Long> newOrder = getNewOrder();
Set<Item> reorderedSet = reorderCollection(setToReorder,
newOrder,
new Mapper<Item, Long>() {
@Override
public Long map(Item item) {
return item.getId();
}