英文:
Java streams groupingBy with condition
问题
如何按一定范围的可能值对列表进行分组?
如果我有一个类Foo
class Foo{
int value;
}
和一个Foo列表List<Foo>
,然后
list.stream().collect(Collectors.groupingBy(Foo::getValue));
将把具有相同值的Foo收集到一个组中。但我想将一定范围的值分组到一个组中。例如
值< 5 分在组“A”中
值> 5 && < 25 分在组“B”中
值>= 25 分在组“C”中
或者另一个例子:假设我有一个整数列表:
List<Integer> list = List.of(2,3,4,9,11,17,28,29,32);
list.stream().collect(Collectors.groupingBy(
classifier,
Collectors.toList()));
我尝试将分类器的内容放入以下形式:
i < 5 ? "A": i >= 5 && i < 25 ? "B" : "C";
这会导致编译错误。如何做到这一点?
英文:
How to group a list by a range of possible values?
If I have a class Foo
class Foo{
int value;
}
and a list of foos List<Foo>
list then
list.stream().collect(Collectors.groupingBy(Foo::getValue));
will collect my foos which have same value into one group. But I want to group a range of values into one group. For example
values < 5 in group "A"
values > 5 && < 25 in group "B"
values >= 25 in group "C"
Or another example: Asume I have a list of Integer:
List<Integer> list = List.of(2,3,4,9,11,17,28,29,32);
list.stream().collect(Collectors.groupingBy(
classifier,
Collectors.toList()));
I have tried to put something like to classifier
i < 5 ? "A": i >= 5 && i < 25 ? "B" : "C";
which gives compilation error. How to do it?
答案1
得分: 6
代替Foo::getValue
,提供一个函数,它给出所属的组:
public class B {
public static String group(int integer) {
if (integer < 5) {
return "A";
} else if (integer < 25) {
return "B";
}
return "C";
}
}
然后:
list.stream().collect(Collectors.groupingBy(B::group));
英文:
Instead of Foo::getValue
, provide a function that give the group it belong to:
public class B {
public static String group(int integer) {
if (i < 5) {
return "A";
} else if (i < 25) {
return "B";
}
return "C";
}
}
Then:
list.stream().collect(Collectors.groupingBy(B::group));
答案2
得分: 1
确保在您的分类器中返回该值。
这应该适用于您上面的示例:
List<Integer> list = Arrays.asList(2,3,4,9,11,17,28,29,32);
list.stream().collect(Collectors.groupingBy(i -> {
if (i < 5) return "a";
else if (i < 25) return "b";
return "c";
}, Collectors.toList()));
英文:
Make sure in your classifier you have it return the value.
This should work for your example above:
List<Integer> list = Arrays.asList(2,3,4,9,11,17,28,29,32);
list.stream().collect(Collectors.groupingBy(i -> {
if (i < 5) return "a";
else if (i < 25) return "b";
return "c";
}, Collectors.toList()));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论