Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find Sum of Map Items in List of Map

I have List<Map<String,Integer>>

Where each items in list consist of items of Map, something like below (just for representation)

List[0].Map[0]("Sam",10)
        Map[1]("Sarah",12)
        Map[2]("Remi", 18)

List[1].Map[0]("Darren",13)
        Map[1]("Peter",19)
        Map[2]("Larry", 21)

Is there a way to check total sum of map greater than 50 and get the index of the list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output : 1 , as items in Map on List[1] exceeds 50

I can get what I needed in with multiple for loops but is there a better approach ?

>Solution :

Yes, you can use the Stream API to achieve this:

int index = IntStream.range(0, list.size())
                     .filter(i -> list.get(i).values().stream().mapToInt(Integer::intValue).sum() > 50)
                     .findFirst()
                     .orElse(-1);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading