First let's introduce the problem:
I have a list like [{10,18}, {19,25}, {26,50}]
and i have an input (n), when (n) inside one of objects in a list i will get this object and when (n) not higher then all objects in a list I want to get the higher object.
Take this list for example List<MyObject> list = [{10,18}, {19,25}, {26,50}]
;
when (n) = 5 ==> I will get {}
when (n) = 10 ==> I will get {10,18}
when (n) = 18 ==> I will get {10,18}
when (n) = 23 ==> I will get {19,25}
when (n) = 45 ==> I will get {26,50}
when (n) = 52 ==> I will get {26,50}
My code works fine, and I want a review.
I have a class Demo
:
public class Demo {
int age1;
int age2;
//getters and setters and constr
}
And a list of demos like
List<Demo> demos = new ArrayList<>();
demos.add(new Demo(11, 12));
demos.add(new Demo(13, 15));
I want to get demo object by value inside interval.
For example, int result = 13;
I get first object.
When I have value higher then all the objects in the list, then I should get the object containing the highest value.
I have the logic in an interface with implementation.
public interface MyDemo {
Function<Integer, Predicate<Demo>> checkBetweenInterval = value -> o -> value >= o.getAge1() && value <= o.getAge2();
List<Demo> toListTraitement(List<Demo> demos, int number);
default Optional<Demo> getDemo(List<Demo> demos, int number){
return toListTraitement(demos, number).stream().filter(checkBetweenInterval.apply(number)).findFirst();
}
default Optional<Demo> getIfInLastObject(List<Demo> demos, int number){
Demo last = demos.get(demos.size() - 1);
if(number >= last.getAge2()) {
return Optional.of(last);
}
else {
return null;
}
}
default Optional<Demo> getFinalResult(List<Demo> demos, int number) {
Optional<Demo> demo = getDemo(demos, number);
if(demo.isPresent()) {
return demo;
}
else {
return getIfInLastObject(demos, number);
}
}
}
Is this the right approach? Can I do better?
[{11, 12}, {13, 15}]
what should be the answer for inputs 5, 11, 12, 13, 15, 55? (Some of them I already understood, I'm saying if you add these examples into your question, it will be helpful.) \$\endgroup\$n
is on interval boundaries, and whenn
is lower than all intervals. So in your example of[{10,18}, {19,25}, {26,50}]
, what will be the answer for 5, 10, 18 ? \$\endgroup\$