ArrayList排序

ArrayList排序:Comparator

// 按照id排序-->从小到大排序:userId1 > userId2 return 1; 
// userId1 < userId2 return -1; userId1 = userId2 return 0;    
private void ascendingOrder(List userList) {    
  Comparator comparator1 = new Comparator() {          
    @Override        
    public int compare(User lhs, User rhs) {            
        int userId1 = lhs.userId;            
        int userId2 = rhs.userId;            
        if (userId1 > userId2) {                
          return 1;            
        } else if (userId1 < userId2) {                
          return -1;            
        } else {                
        return 0;            
        }        
      }    
  };   

  Collections.sort(userList, comparator1);    
  StringBuilder builder = new StringBuilder();    
  for (User user : userList) {        
    builder.append(user.userId).append(user.userName).append(user.hobby).append("\n");    
  }    
  textView1.setText(builder.toString());
}
// 按照id排序-->从大到小排序:userId1 > userId2 return -1;
//  userId1 < userId2 return 1; userId1 = userId2 return 0;   
private void descendingOrder(List userList) {    
  Comparator comparator2 = new Comparator() {        
  @Override        
  public int compare(User lhs, User rhs) {            
        int userId1 = lhs.userId;            
        int userId2 = rhs.userId;            
        if (userId1 > userId2) {                
        return -1;            
        } else if (userId1 < userId2) {                
        return 1;            
        } else {                
        return 0;            
        }        
      }    
  };    

  Collections.sort(userList, comparator2);    
  StringBuilder builder = new StringBuilder();    
  for (User user : userList) {        
    builder.append(user.userId).append(user.userName).append(user.hobby).append("\n");    
  }    
  textView2.setText(builder.toString());
}

效果图:

ArrayList排序_第1张图片

你可能感兴趣的:(ArrayList排序)