• Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating a map of maps from a list using Java 8 streams  RSS feed

 
Pricop Adrian
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
   Hello everyone,
I've come around this grave issue, and the various solutions i found on the internet didn't seem to work for me.
I have a class called MonitoredData, which looks like this:
I also have a list<MonitoredData> filled with such objects.
The idea is to create a Map<Long, Map<String, Long>> using a stream from the list of MonitoredData. What i've tried so far is:
It's throwing me alot of errors.
The key of the first map is MonitoredData::getDayOfYear and the key to the second map is MonitoredData::getActivityLabel. The value of the second data should be the number of times the certain activity has been found in that specific day.
Thanks in advance, tell me if there's something else i need to tell you.
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're almost there. You're using the toMap() collector, but that method requires you to pass a value-extractor function. Instead, you pass it a collector that counts the number of elements in the downstream. you should be using groupingBy() instead of toMap().

Using method handles instead of lambdas and a static import for Collectors, that leaves you with:
 
Pricop Adrian
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
   Absolutely amazing, i've been spending the last hour with this. Thanks a million, my friend, this did help.
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Glad it helped. Welcome to CodeRanch by the way!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!