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

groupingBy with Boolean but add custom String as Key

I am having the below code and doing groupingBy based on boolean

Map<Boolean, List<Test>> products = testList
        .stream()
        .collect(Collectors.groupingBy(Test::isValidUser));
        

I want to collect it as Map<String, List<Test> .

Based on the boolean value, want to add the custom key as "Valid" and "Invalid".

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

If the isValidUser true, want to add the key as "Valid", else key should be "Invalid"

Any possibility to do this in Java 11?

Note: without adding the String variable in Test class

>Solution :

You may do it using the ternary operator in the key classifier function in the groupingBy collector. Here’s how it looks.

Map<String, List<Test>> products = testList.stream()
        .collect(Collectors.groupingBy(t -> t.isValidUser() ? "Valid" : "Invalid"));
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