如何解决有没有办法重构或改进这段代码?
主要内容:
public static void main(String[] args) {
GroupOfUsers group = new GroupOfUsers();
List<String> users = group.getUsers();
System.out.println("The users are: " + users);
}
类 GroupOfUsers:
public class GroupOfUsers {
private static HashMap<String,Integer> usersWithPoints = new HashMap<String,Integer>() {{
put("User1",800);
put("User2",550);
put("User3",20);
put("User4",300);
}};
public List<String> getUsers() {
List<String> users = new ArrayList<String>();
//Sorting users by points
usersWithPoints.entrySet()
.stream()
.sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
.forEachOrdered(x -> users.add(x.getKey()));
//Capitalizing the names of the users
List<String> usersCapitalized = new ArrayList<String>();
users.forEach(x -> usersCapitalized.add(x.toupperCase()));
return usersCapitalized;
}
}
问题:
解决方法
不要试图避免创建对象。您正在与用户打交道,因此创建一个 User 对象。代码将更易于阅读和维护。让我告诉你:
public class User {
private String name;
private int points;
public User(String name,int points) {
this.name = name;
this.points = points;
}
public String getName() {
return this.name;
}
public int getPoints() {
return this.points;
}
}
List<User> usersWithPoints = Arrays.asList(
new User("User1",800),new User("User2",550),new User("User3",20),new User("User4",300)
);
return usersWithPoints
.stream()
.sort(Comparator.comparingInt(User::getPoints).reversed())
.map(User::getName)
.map(String::toUpperCase)
.collect(Collectors.toList());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。