L-Samuels
L-Samuels

Reputation: 2832

Java 8. List of objects. Want to keeps distincts based on property based on a rule

Does anyone know how to succinctly write a java 8 type distinct function to stream over a list of user clicks and make distinct (based on url) but keep the one with the later timestamp?

action=click, url=www.google.com, timestamp=10
action=click, url=www.google.com, timestamp=20
action=click, url=www.abc.com/123, timestamp=10
action=click, url=www.grassisgreener.com, timestamp=10
action=click, url=www.grassisgreener.com, timestamp=46

The final outcome should be

action=click, url=www.google.com, timestamp=20
action=click, url=www.abc.com/123, timestamp=10
action=click, url=www.grassisgreener.com, timestamp=46

Upvotes: 1

Views: 102

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

One idea would be to collect the content of the list into a map, where the key for each element is the url, the value the user's click metadata and the function used to resolve the collision will retains the input with the highest timestamp:

.stream().collect(toMap(e -> e.getUrl(),
                        e -> e,
                        (e1, e2) -> e1.getTimestamp() > e2.getTimestamp() ? e1 : e2));

From there, you can take the values of this map which will give you a collection of the latest clicks for each different url.

Upvotes: 3

Related Questions