Your code would be
public static void main(String[] args){
String[] seq = new String[]{"1","2","3","1.5","5","6","7","4","12","13","1.75","4.5"};
String baseS = "4.5";
double baseD = Double.parseDouble(baseS);
double candidateD = 1;
for(String item: seq){
double itemD = Double.parseDouble(item);
if(itemD < baseD && itemD > candidateD){
candidateD = itemD;
}
}
System.out.println(new DecimalFormat("#.##").format(candidateD));
}
if you need to take just the nearest value (not necessarily minimal one) then the code would look much more complex:
public static void main(String[] args){
String[] seq = new String[]{"1","2","3","1.5","5","6","7","4","12","13","1.75","4.5"};
List<Double> seqD = new ArrayList<>();
// Convert to list of doubles
for(String item: seq){
seqD.add(Double.parseDouble(item));
}
// Sort list
seqD.sort(new Comparator<Double>() {
@Override
public int compare(Double o1, Double o2) {
double res = o2.doubleValue() - o1.doubleValue();
if(res < 0){
return 1;
}else if (res > 0){
return -1;
}
return 0;
}
});
// Take some base value
String base = "1.5";
int baseIndex = seqD.indexOf(Double.valueOf(base));
if(baseIndex >= 0){
Double closest = null;
int rightIndex = baseIndex;
int leftIndex = baseIndex;
// Calclulate index of the nearest "right" value that is not equal to base value
while (rightIndex < seqD.size() - 1 && seqD.get(rightIndex).equals(Double.valueOf(base))){
rightIndex++;
}
// Calculate index of the nearest "left" value that is not equal to base value
while (leftIndex > 0 && seqD.get(leftIndex).equals(Double.valueOf(base))){
leftIndex--;
}
// Handle corner cases when there is no left or right value (take either first or last element as "base")
if(leftIndex == baseIndex){
closest = seqD.get(rightIndex);
}else if(rightIndex == baseIndex){
closest = seqD.get(leftIndex);
}else{
// Handle regualr situation when there are some left and right values
closest = Math.abs(seqD.get(rightIndex)-seqD.get(baseIndex)) < Math.abs(seqD.get(leftIndex) - seqD.get(baseIndex)) ? seqD.get(rightIndex) : seqD.get(leftIndex);
}
System.out.println(new DecimalFormat("#.##").format(closest.doubleValue()));
}
}