lista de filtros basado en predicado distinto y segundo

Saurabh Kumar:

Mis objeto se ve como siguiente

Store {
   String shopId;
   long distance;
}

Tengo una lista de tiendas.

List<Store> storesList = Arrays.asList(
    new Store (1, 1),
    new Store (1, 5),
    new Store (2, 2),
    new Store (1, 1), // this is duplicate
    new Store (1, 2),
    new Store (1, 1), // this is duplicate
    new Store (3, 7)
    new Store (3, 5)
);

Salida

Store {shopId=1, distance=1}  // its fine to have any one among 3 duplicates
Store {shopId=2, distance=2}
Store {shopId=3, distance=5}

Puedo llamar a mi propio método distint como seguir

private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}

y filtrarla como esto

List<Store> stores= storesList .stream()
        .filter(distinctByKey(pr -> Arrays.asList(pr.getShopId())))
        .collect(toList());

pero la forma de filtrarla al mismo tiempo por la distancia más pequeña también?

Eugene:
 storesList.stream()
           .collect(Collectors.toMap(
                Store::getShopId,
                Function.identity(),
                BinaryOperator.minBy(Comparator.comparingLong(Store::getDistance))
              ))
           .values()
           .forEach(System.out::println);

Puede combinar estas mismas Stores (por storeId), donde se podría decir que cuando la fusión que tomaría el más pequeño distanceentre dos tiendas.

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=227504&siteId=1
Recomendado
Clasificación