I made some suppositions from your implementation :
public class Range {
private final int from;
private final int to;
}
// - - AND - -
public class Tuple {
private final Range rf;
private final Range rt;
}
I propose to add the following methods :
// In Range class
public boolean isValid(int x) {
return (from <= x) && (x <= to);
}
//-----------------------------------------------------------------
// In Tuple class
public boolean isValid(int x, int y) {
return rf.isValid(x) && rf.isValid(y);
}
And a class to manage your stuff :
public class TupleGestion {
private static final Map<Tuple, String> map = new HashMap<>();
private static String getValue(int x, int y) {
return map.get(map.keySet().stream()
.filter(key -> key.isValid(x, y)).findAny().orElse(null));
}
public static void main(String[] args) {
map.put(new Tuple(new Range(25, 75), new Range(25, 75)), "foo");
System.out.println(getValue(0, 0)); // null
System.out.println(getValue(50, 0)); // null
System.out.println(getValue(0, 50)); // null
System.out.println(getValue(50, 50)); // foo
}
}
This will read over the key and find one which correspond to your attemp, have the 2 ints
into both range
EDIT - Performance :
- add 6000 random elements in the map :
<5ms
- use
nanoTime()
to compute the time it takes for use getValue()
:
- only
getValue()
for 20000 times : 100ms< t < 150ms
System.out.println(getValue())
20000 times : 850ms< t <1sec
You were asking about 3000 elements and 1000 getValue()
: <5ms
(200 times lower than 1sec)