有没有办法重构或改进这段代码?

问题描述

有下一个代码

主要内容

    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());