简体   繁体   English

将列表拆分为 X 值的插槽

[英]Split list into slots of X value

I have a list in my Java app, it is a list of custom objects, so let us say the objects have property called A, then another object which is always the same has another value, called B. You make a calculation between each A element in the list and the fixed B value, and you get a double value, and those values range from 0 to infinite, Id need to split the objects by those values into slots, for example, in the final sorted list the objects that its calculation result ranges from 0 to 50 should come first in the sorted list, then those who range between 50 and 100, etc. How can I achieve this?我的 Java 应用程序中有一个列表,它是一个自定义对象列表,因此假设对象具有称为 A 的属性,然后另一个始终相同的对象具有另一个值,称为 B。您在每个 A 之间进行计算列表中的元素和固定的 B 值,你得到一个 double 值,这些值的范围从 0 到无限,Id 需要通过这些值将对象拆分成槽,例如,在最终的排序列表中,它的对象计算结果范围从 0 到 50 应该在排序列表中排在最前面,然后是那些范围在 50 到 100 之间的结果,等等。我怎样才能做到这一点?

double valueA = 40; //some random number as an example

List<MyCustomType> list = ...

now each item in the list has a prop with a value that gets compared to valueA, therefore each item in the list will have a different calculated value, that is what I want to sort.现在列表中的每个项目都有一个道具,其值与 valueA 进行比较,因此列表中的每个项目将具有不同的计算值,这就是我想要排序的。

You can use Java 8 streaming functionality to split the data as per your requirement, below is the sample for same:您可以使用 Java 8 流功能根据您的要求拆分数据,以下是相同的示例:

   public class DateTest {

        public static void main(String[] args) {

            List<Division> divList = new ArrayList<>();

            divList.add(new Division(50, 7));
            divList.add(new Division(718, 9));
            divList.add(new Division(38, 9));
            divList.add(new Division(37, 4));

            Function<Division, Integer> condition = s -> {
               return ((s.x / s.y) > 50) ? 1 : 0;
            };
            Map<Integer, List<Division>> collect = divList.stream().collect(
                    Collectors.groupingBy(condition));

            System.out.println(collect.toString());
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM