Da pra implementar melhor, mas também, como disseram, vai da preferência. Se tiver usando Java 8 (por causa dos lambdas), da pra fazer algo assim
`public class Ranges {
private static final Set<Integer> RANGE1 = Sets.newHashSet(1, 2, 3, 4, 5);
private static final Set<Integer> RANGE2 = Sets.newHashSet(6, 7, 8, 9, 10);
private static final Set<Integer> RANGE3 = Sets.newHashSet(11, 12, 13, 14, 15);
private static final Set<Integer> RANGE4 = Sets.newHashSet(16, 17, 18, 19, 20);
private static final Set<Integer> RANGE5 = Sets.newHashSet(21, 22, 23, 24, 25);
private static final Set<Integer> RANGE6 = Sets.newHashSet(26, 27, 28, 29, 30);
private static final Set<Set<Integer>> RANGES = Sets.newHashSet(RANGE1, RANGE2, RANGE3, RANGE4, RANGE5, RANGE6);
public void doSomething() {
Map<Set<Integer>, Integer> map = ImmutableMap.of(
RANGE1, 3,
RANGE2, 5,
RANGE3, 8,
RANGE4, 10,
RANGE5, 15
);
System.out.println(map.get(contains(12))); // returns 8
System.out.println(map.get(contains(1))); // returns 3
System.out.println(map.get(contains(23))); // returns 15
System.out.println(map.get(contains(6))); // returns 5
}
private Set<Integer> contains(Integer day) {
return RANGES.parallelStream().flatMap(r -> RANGES.stream())
.filter(range -> range.contains(day)).findFirst().get();
}
public static void main(String[] args) {
Ranges ranges = new Ranges();
ranges.doSomething();
}
}`
No caso aí, usei o Guava pra Sets, ImmutableMap.
Caso não dê preferencia em fazer isso… eu pelo menos criaria os Sets com os ranges, já acho que ficaria mais limpo.
PS: Da pra melhorar mais ainda, no caso de passar o valor fixo, crio alguma interface e passo no meu map, ficando mais dinâmico o retorno. Ex:
`public class Ranges {
private static final Set<Integer> RANGE1 = Sets.newHashSet(1, 2, 3, 4, 5);
private static final Set<Integer> RANGE2 = Sets.newHashSet(6, 7, 8, 9, 10);
private static final Set<Integer> RANGE3 = Sets.newHashSet(11, 12, 13, 14, 15);
private static final Set<Integer> RANGE4 = Sets.newHashSet(16, 17, 18, 19, 20);
private static final Set<Integer> RANGE5 = Sets.newHashSet(21, 22, 23, 24, 25);
private static final Set<Integer> RANGE6 = Sets.newHashSet(26, 27, 28, 29, 30);
private static final Set<Set<Integer>> RANGES = Sets.newHashSet(RANGE1, RANGE2, RANGE3, RANGE4, RANGE5, RANGE6);
public void doSomething() {
Map<Set<Integer>, Calcular> map = ImmutableMap.of(
RANGE1, () -> 3,
RANGE2, () -> 5,
RANGE3, () -> 8,
RANGE4, () -> 10,
RANGE5, () -> 15
);
System.out.println(map.get(contains(12))); // returns 8
System.out.println(map.get(contains(1))); // returns 3
System.out.println(map.get(contains(23))); // returns 15
System.out.println(map.get(contains(6))); // returns 5
}
private Set<Integer> contains(Integer day) {
return RANGES.parallelStream().flatMap(r -> RANGES.stream())
.filter(range -> range.contains(day)).findFirst().get();
}
public static void main(String[] args) {
Ranges ranges = new Ranges();
ranges.doSomething();
}
interface Calcular {
Integer call();
}
}`