尽管开发足球/足球应用程序,但是我需要一个可以索引并包含两个值的数据结构。如果还可以排序,那将是很好。这两个值是玩家名称及其评分(满分10分)。例如
(约翰·史密斯,9岁)。
HashMaps的问题在于,即使它将包含两个值,数据本身也不被索引。
谢谢
答案 0 :(得分:3)
Map<String, Integer>
将玩家姓名与其值相关联的地图应该可以完成此任务:
// Initialize the player map
Map<String, Integer> players = new HashMap<>();
players.put("John", 2);
players.put("Paul", 8);
players.put("Andrew", 5);
// Print all players sorted by name
players.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEach(System.out::println);
// Print all players sorted by rating
players.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEach(System.out::println);
// Find a player by name and print their details
System.out.println(players.get("Paul"));
但是,无法通过索引访问映射条目。继续阅读。
List<Player>
或者,您可以定义一个代表玩家的类:
public class Player {
private String name;
private Integer rating;
public Player(String name, Integer rating) {
this.name = name;
this.rating = rating;
}
// Getters, setters and toString() methods
}
然后您将具有以下内容:
// Initialize the player list
List<Player> players = new ArrayList<>();
players.add(new Player("John", 2));
players.add(new Player("Paul", 8));
players.add(new Player("Andrew", 5));
// Print all players sorted by name
players.stream()
.sorted(Comparator.comparing(Player::getName))
.forEach(System.out::println);
// Print all players sorted by rating
players.stream()
.sorted(Comparator.comparing(Player::getRating))
.forEach(System.out::println);
// Find a player by name and print their details
String filter = "Paul";
players.stream()
.filter(player -> player.getName().equals(filter))
.findFirst()
.ifPresent(System.out::println);
// Find a player by index and print their details
System.out.println(players.get(0));
答案 1 :(得分:2)
定义自己的类,如下所示:
class Player {
String name;
float rating;
// Class methods
}
在主类中创建List
个Player
中的一个{1>}:
List<Player> players = new ArrayList<>();
使用自定义Comparator
进行排序:
Comparator<Player> comparator = new Comparator<Player>() {
@Override
public int compare(Player p1, Player p2) {
//Sorting logic
}
};
players.sort(comparator);