java.util包的聚合框架应用
java.util包的集合框架应用
输出结果:
第二种方法,感觉思路更清晰,运算复杂度更小:getCountByName方法
.
package mix.test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @function 【武汉】歪尘(531314208) 2011-10-26 20:55:54<BR> * set集合有一些javabean,我要怎么进行过滤?<BR> * name 数量 <BR> * a 10<BR> * b 3<BR> * a 3<BR> * b 5<BR> * * name 数量 <BR> * a 13<BR> * b 8<BR> * * @author ocaicai@yeah.net * * @date 2011-10-27 */ public class ListTest { /** * @param args */ public static void main(String[] args) { List<Product> list = genernateProduct(); list = getCountByName(list); System.out.println(Arrays.toString(list.toArray())); } public static List<Product> genernateProduct() { List<Product> list = new ArrayList<Product>(); list.add(new Product("a", 10)); list.add(new Product("b", 3)); list.add(new Product("a", 3)); list.add(new Product("c", 5)); list.add(new Product("b", 5)); list.add(new Product("c", 7)); return list; } public static List<Product> getCountByName(List<Product> list) { List<Product> targetList = new ArrayList<Product>(); int count = 0; Product product = null; // 去除掉重复name,得到有序的name Set<String> nameSet = new HashSet<String>(); List<String> nameList = new ArrayList<String>(); for (int i = 0; i < list.size(); i++) nameSet.add(list.get(i).getName()); for (String name : nameSet) nameList.add(name); Collections.sort(nameList); // 获取每个name的count和 for (String name : nameList) { count = 0; for (int i = 0; i < list.size(); i++) { product = list.get(i); if (product.getName().equals(name)) { count += product.getCount(); list.remove(i); i--; } } targetList.add(new Product(name, count)); } return targetList; } }
package mix.test; public class Product { private String name; private int count; public Product(String name, int count) { super(); this.name = name; this.count = count; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } @Override public String toString() { return this.name + ":" + this.count; } }
输出结果:
[a:13, b:8, c:12]
第二种方法,感觉思路更清晰,运算复杂度更小:getCountByName方法
public static List<Product> getCountByName(List<Product> productList) { List<Product> targetList = new ArrayList<Product>(); Product product = null; // 寻找该name的总count,然后删除该name String name = null; int count = 0; while (productList.size() > 0) { name = productList.get(0).getName(); count = 0; for (int i = 0; i < productList.size(); i++) { product = productList.get(i); if (product.getName().equals(name)) { count += product.getCount(); productList.remove(i); i--; } } targetList.add(new Product(name, count)); } return targetList; }
.