Mezoo Mezoo - 5 months ago 14
Java Question

Best ways to filter on priority value

In a Collection (Iterable), if there are duplicates, I would like filter on priority value.

class's data représentation can be like to :

[
{
"uuid": "56a00526-871f-43d4-86fe-0df1773f5cdf",
"entry": "CASSIER",
"rate": {
"uuid": "0b264f4d-3f3f-4e39-3f3f-3f53263f303d",
"type": 2,
"rate": 430
}
},
{
"uuid": "663f5d3f-3f3f-48da-a743-3f7b3f753e65",
"entry": "CASTET",
"rate": {
"uuid": "3fdf9f2c-3f3f-4e3f-3f3f-263fe29d8d07",
"type": 1,
"rate": 13
}
},
{
"uuid": "8eae8c39-d667-4cc5-9b91-544454961399",
"entry": "CASTET",
"rate": {
"uuid": "133f0315-413f-493f-3f24-3f3f6d3f5874",
"type": 2,
"rate": 345
}
},
{
"uuid": "6D680178-9B05-4744-A004-163D4B3E1E84",
"entry": "JOHN",
"rate": {
"uuid": "EE877ABD-932F-4B4C-AB23-B324363B0B60",
"type": 1,
"rate": 13
}
}
]


Excepted result (priority : rate.type = 2) :

[
{
"uuid": "56a00526-871f-43d4-86fe-0df1773f5cdf",
"entry": "CASSIER",
"rate": {
"uuid": "0b264f4d-3f3f-4e39-3f3f-3f53263f303d",
"type": 2,
"rate": 430
}
},
{
"uuid": "8eae8c39-d667-4cc5-9b91-544454961399",
"entry": "CASTET",
"rate": {
"uuid": "133f0315-413f-493f-3f24-3f3f6d3f5874",
"type": 2,
"rate": 345
}
},
{
"uuid": "6D680178-9B05-4744-A004-163D4B3E1E84",
"entry": "JOHN",
"rate": {
"uuid": "EE877ABD-932F-4B4C-AB23-B324363B0B60",
"type": 1,
"rate": 13
}
}
]


Do something with Java Stream exists ?

Answer

Finally, I have used Predicate to filter an Iterable and a Stream filter after sorting Iterable by rate.type:

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

Stream s = StreamSupport.stream(registrations.spliterator(), false);
s.filter(distinctByKey((Registration r) -> r.getEntry().getUuid())).collect(Collectors.toList());