Java流根据条件分组。

huangapple go评论116阅读模式
英文:

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 &lt; 5) {
             return &quot;A&quot;;
        } else if (i &lt; 25) {
            return &quot;B&quot;;
        }
        return &quot;C&quot;;
    }
}

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&lt;Integer&gt; list = Arrays.asList(2,3,4,9,11,17,28,29,32);
list.stream().collect(Collectors.groupingBy(i -&gt; {
    if (i &lt; 5) return &quot;a&quot;;
    else if (i &lt; 25) return &quot;b&quot;;
    return &quot;c&quot;;
  }, Collectors.toList()));

huangapple
  • 本文由 发表于 2020年7月21日 19:05:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63013148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定