java中的ArrayList,只执行一次操作

发布于 2024-12-08 00:37:19 字数 150 浏览 0 评论 0原文

出于某种原因,我在这个问题上画了一个空白。我有一个包含 CD 的 ArrayList(其中一些名称相同),我想打印一个字符串来告诉我每张 CD 有多少张。例如,字符串“您有:(1) AlbumOne、(2) AlbumTwo、(1) AlbumThree”等。CD 未排序。我该怎么做?

For some reason, I'm drawing a blank on this one. I have an ArrayList that contains CDs (some of them identical in name) and I want to print a String that tells how many I have of each CD. For example, a string that says "You have: (1) AlbumOne, (2) AlbumTwo, (1) AlbumThree" etc. The CDs are not sorted. How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤独陪着我 2024-12-15 00:37:19

一种方法是循环遍历数组,并使用将对象用作键、将值用作计数的映射。因此

Map<YourObject, Integer> counter ...

,当您循环遍历数组时,请在数组中当前对象的计数器上执行 get 操作。如果得到 null,则将映射中该存储桶的值初始化为 1。如果有值,则递增它。然后您可以循环地图以获取读数。

请注意,如果您使用 Hashmap,您的对象必须正确实现 hashcodeequals 方法。您不必使用您的对象,如果它有键或其他一些区分字段,则地图中的键可以是......

One way to do it is to loop thru the array, and use a map that uses the objects as keys and the values as counts. So

Map<YourObject, Integer> counter ...

As you loop thru the array, do a get on the counter for the current object in the array. If you get null, initialize the value at that bucket in the map to be 1. If you have a value, increment it. Then you can loop over the map to get your readout.

Note that if you use a Hashmap, your objects have to implement the hashcode and equals method properly. You don't have to use your object, if it has keys or some other distinguishing field, the keys in your map can be that...

燃情 2024-12-15 00:37:19
//aggregate details
Map<String, Integer> albumCounts = new HashMap<String, Integer>();
for (String album : albums) {
    Integer count = albumCounts.get(album); 
    if (count == null) {
        count = 0;
    }
    albumCounts.put(album, count + 1);
}

//print stats
System.out.println("You have:");
for (String album : albums) {
   System.out.println("(" + albumCounts.get(album) + ") " + album);
}
//aggregate details
Map<String, Integer> albumCounts = new HashMap<String, Integer>();
for (String album : albums) {
    Integer count = albumCounts.get(album); 
    if (count == null) {
        count = 0;
    }
    albumCounts.put(album, count + 1);
}

//print stats
System.out.println("You have:");
for (String album : albums) {
   System.out.println("(" + albumCounts.get(album) + ") " + album);
}
终难愈 2024-12-15 00:37:19

不要对地图感到困惑。使用 Map 适合解决此类问题(正如您所发布的),因此请访问 链接(教程)并阅读/了解地图。

Don't get confused about the Map. Use of Map is appropriate to solve such a problem (as you have posted) So please visit this link (tutorial) and read/learn about Map.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文