List排序

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class ListTest {

	/**
	 * @param args
	 */
	/*
	 * 去除List重复数据
	 * 1、removeDuplicateObj 无序
	 * 2、removeDuplicate
	 * 3、removeDuplicateSet 无序
	 */
	private   List   removeDuplicateObj(List   list)   {          
        Set someSet=new HashSet(list);      

        //   将Set中的集合,放到一个临时的链表中(tempList)      
        Iterator iterator=someSet.iterator();      
        List tempList=new ArrayList();      
        int i=0;      
        while(iterator.hasNext()){
        	tempList.add(iterator.next().toString());      
            i++;                                         
        }      
        return   tempList;      
  }
	public   static   List  removeDuplicate(List list)  {   
	      for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {   
	          for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {   
	               if  (list.get(j).equals(list.get(i)))  {   
	                  list.remove(j);   
	                }    
	            }    
	          }    
	        return list;   
	    }
	public   static   List  removeDuplicateSet(List list)  {   
        HashSet h  =   new  HashSet(list);   
        list.clear();   
        list.addAll(h);   
        return list;   
     } 
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		ListTest listTest=new ListTest();
		List<User> list1=new ArrayList<User>();
		List<String> list2=new ArrayList<String>();
		List list3=new ArrayList();
		User user1=new User("a1","a11");		
		User user2=new User("a1","a12");
		User user3=new User("a1","a13");
		User user4=new User("a2","a21");
		User user5=new User("a2","a22");
		list1.add(user1);list1.add(user2);list1.add(user3);
		list1.add(user4);list1.add(user5);

		for(int i=0;i<list1.size();i++){
		    User user=(User) list1.get(i);
            list2.add(user.getId());
	    }
		list3=listTest.removeDuplicate(list2);
		for(int i=0;i<list3.size();i++){
			String a=(String)list3.get(i); 
			System.out.println("item="+a+"  ");			
			for(int j=0;j<list1.size();j++){				
				
				User user=(User) list1.get(j);
				String b=(String)user.getId();
				if(a.equals(b)){
					System.out.print("subitem="+user.getName()+" ");
				}
				
			}
			System.out.println();
		}
	}

}
  class User{
	private String id;
	private String name;
	
	public User(){
		
	}
    public User(String id,String name){
		this.id=id;
		this.name=name;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
  }


 

 结果:

item=a1  
subitem=a11 subitem=a12 subitem=a13 
item=a2  
subitem=a21 subitem=a22

 

 

你可能感兴趣的:(J#)