问题
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.
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"
.
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.
回答1:
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.
回答2:
You can use the TreeMap object where the Fruit name is the key and value is the number of times it has been seen.
You iterate through the array fruit by fruit, using say a foreach loop and update that fruit's value in the TreeMap. At the end you print the key and its value. Since we've used a TreeMap the keys will be in sorted order.
回答3:
What have you tried ? Create instance of HashMap, where keys are fruits names and values are fruits occurrence. Iterate over your your array, on every iteration, add new fruit to your Map or increment the number of occurrence of existing key.
Then iterate over HashMap, and build your String
回答4:
If everything is in a single ArrayList and you know the fruit that you are expecting you could use
ArrayList<String> fruits = new ArrayList<>();
//load some fruit code [ .. ]
int orangeOccurrences = Collections.frequency(fruits, "orange");
but Map is definitively the more correct approach.
来源:https://stackoverflow.com/questions/10498262/java-arraylist-item-counter-ie-apple-3%c3%97banana-2%c3%97orange