Alvin
Alvin

Reputation: 8499

get a list of unique date from the stream grouping

I have data:

id|date
1 |12-12-2021
2 |12-12-2021
3 |13-12-2021

Want to get a list of dates: ["12-12-2021", "13-12-2021"]

Using stream, I can get a map:

txs.stream().collect(Collectors.groupingBy(g -> g.getDate()));

I would like to convert to list in from the stream above.

Upvotes: 1

Views: 1094

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40078

If you have the data in Map<Integer,LocalDate> the you can use values() and collect to Set to eliminate duplicates

Set<LocalDate> dates = txs.values().stream().collect(Collectors.toSet())

or using HashSet

new HashSet<>(txs.values());

Upvotes: 1

magicmn
magicmn

Reputation: 1914

groupingBy is not the best choice in your case. Use distinct instead. It will automatically filter out all duplicates.

txs.stream().map(g -> g.getDate()).distinct().collect(Collectors.toList());

Upvotes: 3

Related Questions