简体   繁体   English

如何获取 HashMap 中包含的所有键的特定属性值?

[英]How can I get a specific attribute value for all the keys contained in a HashMap?

I have a Hashmap: Map<String, Paper> numberMapping = new HashMap<>();我有一个哈希图: Map<String, Paper> numberMapping = new HashMap<>();

class Paper String[] author; String[] scores; class Paper String[] author; String[] scores; String[] author; String[] scores;

I want to retrieve all the author of each object contained in the hashmap.我想检索哈希图中包含的每个对象的所有作者。

I tried System.out.print(numberMapping.values().getAuthor());我试过System.out.print(numberMapping.values().getAuthor()); but it's not working, how can I do that?但它不起作用,我该怎么做? Thanks in advance.提前致谢。

You are not seeing a user friendly output cause you are printing String[] objects, which does not have a friendly toString() method.您没有看到用户友好的输出,因为您正在打印 String[] 对象,该对象没有友好的 toString() 方法。

Either use use Set<String> instead of String[] , which has a better implementation, or else assuming Java 8+, a functional way could be:要么使用 use Set<String>而不是String[] ,它具有更好的实现,或者假设 Java 8+,一种功能方式可能是:

Set<String> allAuthors = numberMapping.values()
        .stream()
        .map(paper -> paper.author)
        .flatMap(author -> Arrays.stream(author))
        .collect(Collectors.toSet());
System.out.println(allAuthors);

Also it's common practice to use plurals for variables that refers to Collections.此外,通常的做法是对引用集合的变量使用复数形式。

I'm assuming the overall order of the output doesn't matter to you since you are using a Hashmap to store the values, as pointed out in the comments我假设输出的整体顺序对您来说无关紧要,因为您正在使用Hashmap来存储值,正如评论中所指出的

You could do it in following ways:您可以通过以下方式做到这一点:

List<String[]> authors = ...
for (Paper paper : numberMapping.values()) {
    authors.add(paper.getAuthor());
}
//print authors

Alternatively, you could use Stream api like below:或者,您可以使用 Stream api,如下所示:

System.out.println(numberMapping.values().stream().
                       map(paper -> paper.getAuthor()).
                       collect(Collectors::asList));

Now remember, you have array of authors, hence it might not print correctly as arrays doesn't have inbuilt toString implemented, hence you may need to iterate over each elements and print the authors using Arrays.toString(authors) .现在请记住,您有作者数组,因此它可能无法正确打印,因为数组没有实现内置的 toString,因此您可能需要遍历每个元素并使用Arrays.toString(authors)打印Arrays.toString(authors)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM