0

I have model on my code

public class FulfillmentPurchaseOrder extends Audit implements Serializable {
 @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private Integer id;

    @Column(name = "purchase_order_id")
    private Integer purchaseOrderId;

    @Column(name = "version")
    private Integer version;


    @Column(name = "remarks")
    private String remarks;

    @Column(name = "status")
    private String status;
}

and also I have code like this :

 List<FulfillmentPurchaseOrder> fulfillmentPurchaseOrders = fulfillmentPurchaseOrderRepository.findAll(tickerSpecification);

and then here for my orderBy version field

List<FulfillmentPurchaseOrder> fulfillmentPurchaseOrderSortDescVersion =  fulfillmentPurchaseOrders.stream().sorted(Comparator.comparingInt(FulfillmentPurchaseOrder::getVersion).reversed()).collect(Collectors.toList());

but when I want filter distinctByKey I cannot use it... my question is how to use sorted stream + filtering by distinctByKey ? how to make streams from my list with distinct from purchaseOrderId and orderBy version Desc ?

Prasath
  • 1,233
  • 2
  • 16
  • 38
  • 1
    Your question is unclear. Please elaborate more or read https://stackoverflow.com/help/how-to-ask on how to ask a good question. – bradley101 Dec 16 '21 at 06:11
  • Remember one thing `findAll()` have no argument. – Faheem azaz Bhanej Dec 16 '21 at 06:20
  • yup... i want to get all of from list.. after that i want to filtering use stream – jujil lokoko Dec 16 '21 at 06:24
  • See [Java 8 Distinct by property - Stack Overflow](https://stackoverflow.com/questions/23699371/java-8-distinct-by-property). –  Dec 16 '21 at 06:30
  • First have to override hashcode & equals method with purchaseOrderId. Then you can follow list.stream.distinct().sort(yourComparator). – Prasath Dec 16 '21 at 07:45
  • Why use streams to sort and filter entries with duplicated keys? This is something that should usually be done in the database. – magicmn Dec 16 '21 at 08:15
  • Does this answer your question? [Java 8 Distinct by property](https://stackoverflow.com/questions/23699371/java-8-distinct-by-property) – Prasath Dec 16 '21 at 16:54

1 Answers1

0

Try this

List<FulfillmentPurchaseOrder> finalList =  
            originalList.stream()
            .filter(distinctByKey(FulfillmentPurchaseOrder::getPurchaseOrderId,HashSet::new))
            .sorted(Comparator.comparingInt(FulfillmentPurchaseOrder::getVersion).reversed())
            .collect(Collectors.toList());

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor,Supplier<Set<Object>> supplierSet) {
        Set<Object> set = supplierSet.get();
        return t -> set.add(keyExtractor.apply(t));
    }

Took reference from Java 8 Distinct by property

Prasath
  • 1,233
  • 2
  • 16
  • 38