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

时间:2015-11-18 11:50:35

标签: java arraylist

我有一个数组列表,其中我有一些像

这样的值arraylist
Dim FilterDate    As Date
Dim FilterDateSql As String

FilterDate = DateSerial(Year(Date), Month(Date), 1)
FilterDateSql = Format(FilterDate, "yyyy\/mm\/dd")
DCount("*", "[ComplaintsListMaster]", "[ComplaintDate] >= #" & FilterDateSql & "#")

此处的值:ArrayList<Integer> keyList = new ArrayList<Integer>(treeMap.keySet()); 我得到一些值*62,58,10,6*

现在我想要的是得到每个值的百分比并再次打印出来作为一个类似这样的arraylist

*136.0*

2 个答案:

答案 0 :(得分:0)

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 + "%");
}

答案 1 :(得分:0)

在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));