• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

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

 
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.
 
Saloon Keeper
Posts: 9378
181
  • 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: 9378
181
  • 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!