如何遍历HashMap的所有值并打印出包含搜索词的任何值(How to loop through all values of a HashMap and print out any values co

编程入门 行业动态 更新时间:2024-10-20 09:30:55
如何遍历HashMap的所有值并打印出包含搜索词的任何值(How to loop through all values of a HashMap and print out any values containing a searched term)

我有一张地图:

private HashMap<String, CompactDisc> database;

每个CompactDisc对象都有一个艺术家,我希望用户输入一个字符串并搜索哈希映射并打印出包含该字符串的所有值。 因此,如果我搜索"Jackson" ,我会得到杰克逊5和迈克尔杰克逊(假设他们在CD中)。

I have a map:

private HashMap<String, CompactDisc> database;

Every CompactDisc object has an artist, and I want to have a user enter a string and search through the hash-map and print out ALL values containing the string. So if I searched "Jackson", I would get both The Jackson 5 and Michael Jackson (assuming they are in the CD).

最满意答案

迭代HashMap的值并检查CompactDisc的艺术家名称是否包含指定的字符串。

for (CompactDisc cd : database.values()) { if(cd.getArtist().contains(searchString)){ System.out.println(cd.getArtist()); } }

假设CompactDisk有一个返回String的getArtist()方法。 而searchString是用户指定的字符串。

Iterate through the values of the HashMap and check if the CompactDisc's artist name contains the specified string.

for (CompactDisc cd : database.values()) { if(cd.getArtist().contains(searchString)){ System.out.println(cd.getArtist()); } }

assuming CompactDisk has a getArtist() method that returns a String. And searchString is the string specified by user.

更多推荐

本文发布于:2023-04-29 10:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336358.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   搜索词   HashMap   loop   term

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!