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?
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.
You can use Java 8 streaming functionality to split the data as per your requirement, below is the sample for same:
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());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.