gpt4 book ai didi

可以索引并保存两个值的Java数据结构

转载 作者:行者123 更新时间:2023-12-01 16:45:41 25 4
gpt4 key购买 nike

开发橄榄球/足球应用程序,但是我需要一个可以索引并保存两个值的数据结构。如果也能排序那就太好了。这两个值是玩家姓名和他们的评分(满分 10 分)。例如

(约翰·史密斯,9)。

HashMap 的问题在于,即使它保存两个值,数据本身也没有索引。

谢谢

最佳答案

使用 Map<String, Integer>

将玩家姓名与其值相关联的 map 应该可以完成这项工作:

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

关于可以索引并保存两个值的Java数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51856125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com