001 /* 002 Copyright (C) 2002 Laurent Martelli <laurent@aopsys.com> 003 004 This program is free software; you can redistribute it and/or modify 005 it under the terms of the GNU Lesser General Public License as 006 published by the Free Software Foundation; either version 2 of the 007 License, or (at your option) any later version. 008 009 This program is distributed in the hope that it will be useful, 010 but WITHOUT ANY WARRANTY; without even the implied warranty of 011 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 012 GNU Lesser General Public License for more details. 013 014 You should have received a copy of the GNU Lesser General Public License 015 along with this program; if not, write to the Free Software 016 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ 017 018 package org.objectweb.jac.lib.stats; 019 020 import java.util.Collection; 021 import java.util.Iterator; 022 import org.apache.log4j.Logger; 023 import org.objectweb.jac.core.rtti.FieldItem; 024 025 /** 026 * This class contains static methods to do statistical computations 027 * on collections. 028 */ 029 public class Stats { 030 static Logger logger = Logger.getLogger("stats"); 031 032 /** 033 * Compute average, min and max of a the field of collection's items 034 * 035 * @param stats store result in this structure. Values are not reset to zero. 036 * @param items the items to compute the stats on 037 * @param field the numerical field (float, double or int) to compute the stats of 038 * @return an object containing the average, max and min of field 039 * in items. If there's no item in the collection all values are 0.0 040 */ 041 public static void computeStats(Stat stats, Collection items, FieldItem field) { 042 double average = 0; 043 double sum = 0; 044 double max = 0; 045 double min = 0; 046 long count = 0; 047 long pos = 0; 048 Iterator it = items.iterator(); 049 while (it.hasNext()) { 050 Object item = it.next(); 051 if (item!=null) { 052 double value = ((Number)field.getThroughAccessor(item)).doubleValue(); 053 stats.sum += value; 054 if (count==0 || value<stats.min) 055 stats.min = value; 056 if (count==0 || value>stats.max) 057 stats.max = value; 058 stats.count++; 059 } else { 060 logger.error("computeStats "+field+": null element in collection at position "+pos); 061 } 062 pos++; 063 } 064 } 065 066 public static Stat computeStats(Collection items, FieldItem field) { 067 Stat stat = new Stat(); 068 computeStats(stat,items,field); 069 return stat; 070 } 071 }