public class nrlSports {
public static void main(String[] args){
String[] direction = {"north", "north", "east", "south", "south", "south", "north", "north"};
for(int i=0; i<direction.length; i++) {
int count = 0;
for(int j = 0; j < direction.length; j++)
if(direction[i].equals(direction[j])) {
count++;
}
System.out.println(direction[i] + " (" + count + ")");
}
}
}输出为:北(4)北(4)东(1)南(3)北(4)北(4)
如何删除这些重复的值,使输出看起来像这样:北边(4)、东边(1)、南边(3)
发布于 2013-04-17 23:45:03
这个方法怎么样?
String[] direction = { "north", "north", "east", "south", "south",
"south", "north", "north" };
Map<String, Integer> map = new LinkedHashMap<>();//to preserve order or elements
for (String key : direction) {
if (map.containsKey(key))
map.put(key, map.get(key) + 1);
else
map.put(key, 1);
}
for (Map.Entry<String, Integer> entry : map.entrySet())
System.out.println(entry.getKey() + "(" + entry.getValue() + ")"+
String.format("%"+entry.getValue()+"s", "").replace(' ', '*'));输出
north(4)****
east(1)*
south(3)***发布于 2013-04-17 23:37:12
这可能会有所帮助:
public static void main(String[] args){
String[] direction = {"north", "north", "east", "south",
"south", "south", "north", "north"};
Map<String, Integer> countMap = new HashMap<String, Integer>();
for(int i=0; i<direction.length; i++) {
String key = direction[i];
if(!countMap.containsKey(key)){
countMap.put(key, 1);
}
else
{
countMap.put(key, countMap.get(key)+1);
}
}
System.out.println(countMap);
}发布于 2013-04-17 23:43:34
我认为解决方案不是优化的解决方案,但将工作(通过运行它确认:)
String[] direction = {"north", "north", "east", "south", "south", "south", "north", "north"};
HashMap<String,Integer> myHash = new HashMap<String, Integer>();
for(int i=0; i<direction.length; i++) {
int count = 0;
for(int j = 0; j < direction.length ; j++)
if(direction[i].equals(direction[j])) {
count++;
myHash.put(direction[i], new Integer(count));
}
}
Iterator T = (Iterator) myHash.entrySet().iterator();
while( T.hasNext() )
{
Map.Entry newEntery = (Map.Entry) T.next();
System.out.print(newEntery.getKey() +"("+ newEntery.getValue()+")");
} https://stackoverflow.com/questions/16064114
复制相似问题