一、功能说明
1、实现并列排名:1、1、3、4、4、6
二、实现逻辑
1、将数据封装到User对象中,操作对象进行并列排名处理
三、代码
1、新建User对象
public class User {
private String name;
private Integer age;
private Integer index;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(name, user.name) && Objects.equals(age, user.age) && Objects.equals(index, user.index);
}
@Override
public int hashCode() {
return Objects.hash(name, age, index);
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", index=" + index +
'}';
}
public User() {
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
}
2、Rank 代码
public class RankDemo {
public static void main(String[] args) {
List<User> list = new ArrayList<>();
User user0 = new User("张0", 33);
User user1 = new User("张1", 38);
User user2 = new User("张2", 60);
User user3 = new User("张3", 56);
User user4 = new User("张4", 38);
User user5 = new User("张5", 64);
User user6 = new User("张6", 56);
User user7 = new User("张7", 26);
User user8 = new User("张8", 33);
User user9 = new User("张9", 55);
Collections.addAll(list, user0, user1, user2, user3, user4, user5, user6, user7, user8, user9);
List<User> rankList = list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
int count = 1;
for (int i = 0; i < rankList.size(); i++) {
if (i == 0) {
rankList.get(0).setIndex(count);
count++;
} else {
if (rankList.get(i).getAge().equals(rankList.get(i-1).getAge())){
rankList.get(i).setIndex(rankList.get(i-1).getIndex());
count++;
}else {
rankList.get(i).setIndex(count);
count++;
}
}
}
for (User user : rankList) {
System.out.println("user = " + user);
}
}
}
3、输出展示
Connected to the target VM, address: '127.0.0.1:53811', transport: 'socket'
user = User{name='张7', age=26, index=1}
user = User{name='张0', age=33, index=2}
user = User{name='张8', age=33, index=2}
user = User{name='张1', age=38, index=4}
user = User{name='张4', age=38, index=4}
user = User{name='张9', age=55, index=6}
user = User{name='张3', age=56, index=7}
user = User{name='张6', age=56, index=7}
user = User{name='张2', age=60, index=9}
user = User{name='张5', age=64, index=10}
Disconnected from the target VM, address: '127.0.0.1:53811', transport: 'socket'
Process finished with exit code 0