- package com.test1;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- class aaa{
-
- private String id;
- private int num;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public int getNum() {
- return num;
- }
- public void setNum(int num) {
- this.num = num;
- }
-
- public aaa(){
-
- }
-
- public aaa(String id, int num){
- this.id = id;
- this.num = num;
- }
-
- }
- class ComparatorUser implements Comparator{
- public int compare(Object arg0, Object arg1) {
- aaa user0=(aaa)arg0;
- aaa user1=(aaa)arg1;
-
- //首先比较年龄,如果年龄相同,则比较名字
-
- int flag=user0.getId().compareTo(user1.getId());// 按字典顺序比较两个字符串。
- return flag;
- }
-
- }
- public class Test8 {
- public static void main(String[] args) {
- ArrayList<aaa> list = new ArrayList();
- list.add(new aaa("1", 23));
- list.add(new aaa("2", 45));
- list.add(new aaa("1", 2));
- list.add(new aaa("1", 1231));
- list.add(new aaa("1", 12));
- list.add(new aaa("2", 12));
- list.add(new aaa("3", 2));
- list.add(new aaa("5", 12313));
- list.add(new aaa("4", 1231));
- ComparatorUser comparator=new ComparatorUser();
- Collections.sort(list,comparator);// 根据指定比较器产生的顺序对指定列表进行排序。
-
- int sum = 0;
- String id ="";
- boolean falg = true;
-
- for(aaa a : list){
- if(falg){
- id = a.getId();
- falg = false;
- }
- if(id.equals(a.getId())){
- sum += a.getNum();
- }else{
- System.out.println(id + "*******" + sum);
- id = a.getId();
- sum = 0;
- sum += a.getNum();
- }
- }
- System.out.println(id + "*******" + sum);
- }
- }
复制代码 |