下面的代码从0到100生成100个已排序的随机双打,然后它从这100个数字中计算平均值(平均值)。我的目的是从这些数字中计算10个平均值,然后对它们进行排序,但在很多次尝试中,我得到的还是我的100个排序随机数或1个平均值:(
如何获得这10个平均排序?
public class NewMain {
private static Random rand = new Random();
public static void main(String[] args) {
System.out.println(Arrays.toString(sortowacz(100, 0, 100)));
}
public static Object[] sortowacz(final double length, final double min,
final double max) {
List<Double> nieposortowanaLista = randList(length, min, max);
Collections.sort(nieposortowanaLista);
return nieposortowanaLista.toArray();
}
private static List<Double> randList(final double length, final double min,
final double max) {
List<Double> list = new ArrayList<>();
List<Double> avg = new ArrayList<>();
double sum = 0.0;
for (int i = 0; i < length; i++) {
list.add(min + (max - min) * rand.nextDouble());
}
for (int i = 0; i < list.size(); i++) {
sum += list.get(i);
}
avg.add(sum / list.size());
return list;
}
}
答案 0 :(得分:1)
我不知道您的多重平均值是多少,但要获得一个可以使用的平均值
List<Double> list=new ArrayList<>();
double average = list.stream().mapToDouble(d->d).average().getAsDouble();
答案 1 :(得分:1)
这是您所需的代码,可以计算100个中的10个平均值,并在最后对它们进行排序
public class TestAverages {
public static void main(String... args) {
List<Double> averages = sortowacz(1000, 0, 100);
averages.forEach(System.out::println);
}
public static List<Double> sortowacz(final double length, final double min, final double max) {
List<Double> list = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < length; i++) {
list.add(min + (max - min) * rand.nextDouble());
}
List<Double> averages = new ArrayList<>();
while (!list.isEmpty()) {
List<Double> subList = list.subList(0, (int) (length/10));
double avg = subList.parallelStream().mapToDouble(d -> d).average().getAsDouble();
averages.add(avg);
list.removeAll(subList);
}
return averages;
}
}