简体   繁体   English

从arraylist的总和中获取arraylist值的百分比

[英]Get Percentage of arraylist values from sum of arraylist

i have an array list where i have some value arraylist like 我有一个数组列表,其中有一些值arraylist

ArrayList<Integer> keyList = new ArrayList<Integer>(treeMap.keySet());

Values here: *62,58,10,6* i am getting some if value *136.0* 这里的值: *62,58,10,6*如果值*136.0*我会得到一些

Now what i want is to get % of each value and print them again as an arraylist there something like this 现在我想要的是获取每个值的%,然后再次将它们作为arraylist打印出来,像这样

*40%,34%,16%, 10%*
double sum = 0.0; //if you use version earlier than java-8
//double sum = IntStream.of(keyList).sum(); //if you are using java-8 
for(int i = 0 ; i < keyList.size() ; i++){
  sum += keyList.get(i);    
}
for(int i = 0 ; i < keyList.size() ; i++){
  System.out.println((keyList.get(i)/sum )*100 + "%");
}

In java 8, you can do it like this: 在Java 8中,您可以这样做:

    ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(62, 58, 10, 6));
    double sum = arrayList.stream().mapToInt(Integer::intValue).sum();
    arrayList.stream().forEach(i -> System.out.printf("%.2f%% ", (i / sum) * 100));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM