Java的ArrayList的项目计数器即"苹果,3×香蕉,2×橙" [英] Java ArrayList Item Counter ie "Apple, 3×Banana, 2×Orange"

查看:265
本文介绍了Java的ArrayList的项目计数器即"苹果,3×香蕉,2×橙"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,这不是一个非常复杂的问题,但我是比较新的Java和已经与这一个了一段时间令人费解。

I'm sure this isn't a hugely complex problem but I'm relatively new to java and have been puzzling with this one for a while.

说我有一个包含6字符串值,并让说,他们是一个数组: [苹果,香蕉,香蕉,香蕉,橘,橙] 。我期待建立,将采取这个数组,并返回一个字符串,在上述情况下,作为一种方法:苹果,3×香蕉,2×橙

Say I have an array which contains 6 string values, and lets say they are: [Apple, Banana, Banana, Banana, Orange, Orange]. I am looking to build a method that will take this array and return a string, in the case above, as: "Apple, 3×Banana, 2×Orange".

我将不胜AP preciate一些帮助与此有关。我一直在尝试不同的技术来实现这一点,但倒在了正确的行为对数组的第一次迭代时,检测重复值等。

I would greatly appreciate some help with this. I've been trying different techniques to achieve this but fall down on the correct behavior on the first iteration of the array and when to detect a repeated value ect.

推荐答案

使用地图<字符串,整数> 。迭代这个数组并把字符串作为地图键和柜台值:

Use Map<String, Integer>. Iterate over the array and put strings as Map key and counter as value:

Map<String, Integer> words = HashMap<String, Integer>();
for (String word : words) {
    Integer count = words.get(word);
    count = count == null ? 0 : count++;
    words.put(word, count);
}

现在的话地图包含文字和计数之间的映射。

Now the words map contains mapping between word and its count.

这篇关于Java的ArrayList的项目计数器即&QUOT;苹果,3×香蕉,2×橙&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆