我有以下代码并基于 boolean 值进行分组
Map<Boolean, List<Test>> products = testList
.stream()
.collect(Collectors.groupingBy(Test::isValidUser));
我想 Collection 它为Map<String, List<Test>
.
基于 boolean 值,想要添加自定义键为“有效”和“无效”。
如果 isValidUser
是的,想将 key 添加为“有效”,否则 key 应为“无效”
有没有可能在 Java 11 中做到这一点?
注意:不要在Test类中添加String变量
最佳答案
您可以使用 groupingBy
收集器中的关键分类器函数中的三元运算符来完成。这是它的外观。
Map<String, List<Test>> products = testList.stream()
.collect(Collectors.groupingBy(t -> t.isValidUser() ? "Valid" : "Invalid"));
关于java - groupingBy 带 boolean 值,但添加自定义字符串作为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72255654/