已帮助我在Swift中创建一个函数,以计算ArrayList<Double>
:Swift - Group elements of Array by value (2 by 2, 3 by 3, etc...)
现在,我想用Java进行翻译,但是不确定几行。我该怎么办?
快速版本:
func group(_ array: [Int], coef: Int) -> [Int: Int] {
var result:[Int:Int] = [:]
var start = array[0]
var end = start + coef - 1
var arr = array
while start <= array[array.count - 1] {
let count = arr.filter({ $0 >= start && $0 <= end}).count
result[start] = count
start = end + 1
end = start + coef - 1
arr = Array(arr[count...])
}
return result
}
我在Java中尝试过的操作
private HashMap<Integer, Integer> group(ArrayList<Double> array, int coef, Double start) {
Map<Integer, Integer> result = new HashMap<>();
Double startFrom = start;
Double end = startFrom + Double.valueOf(coef) - 0.1;
ArrayList<Double> arr = array;
// This line
while (startFrom <= array[array.size() - 1]) {
// This line
int count = arr.filter({ $0 >= start && $0 <= end}).count;
// This line
result[Int(start)] = count;
startFrom = end + 1;
end = start + Double.valueOf(coef) - 0.1;
// this line
arr = Array(arr[count...])
}
return result;
}
答案 0 :(得分:0)
在Java中,建议您使用接口而不是您正在使用的实际实现,接口可提供更大的灵活性。如果您使用的是实现,并且必须更改某些内容,那么它很容易中断,因此您的代码将很脆弱。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>