日期:2014-05-20  浏览次数:20777 次

java MAP 中如果 键相同就让值相加是怎么做到的呢?请教各位了!
做法是先通过键从Map中将值取出来
然后通过if else 来判断
if存在
则进行相加
else
直接存入

------解决方案--------------------
这样?
如果每次不是加1,只要你知道是加几就行

Java code


import java.net.URL;
import java.util.*;

public class URLCount{
  
  public static void main(String[] args) throws Exception {
    
    List<URL> urls = Arrays.asList(
        
        new URL("http://www.google.com"),
        new URL("http://www.csdn.net"),
        new URL("http://www.google.com"),
        new URL("http://www.csdn.net"),
        new URL("http://www.google.com"),
        new URL("http://www.google.com"),
        new URL("http://www.csdn.net"),
        new URL("http://www.csdn.net"),
        new URL("http://www.google.com"),
        new URL("http://www.google.com")
    );
    
    Counter<URL> urlCounter = new Counter<URL>();
    
    for(URL url : urls)
      urlCounter.addCount(url, 1);
    
    for(URL key : urlCounter)
      System.out.println(key + " : " + urlCounter.getCount(key));
  }
}

class Counter<K> implements Iterable<K> {
  
  private Map<K, Count> counts = new HashMap<K, Count>();
  
  void addCount(K key, int count) {
    
    if( key == null ) throw new NullPointerException();
    
    Count c = counts.get(key);
    if( c == null ) {
      
      c = new Count();
      counts.put(key, c);
    }
    c.add(count);
  }
  
  int getCount(K key) {
    
    if( key == null ) throw new NullPointerException();
    
    Count c = counts.get(key);
    return c == null ? 0 : c.get();
  }
  
  @Override
  public Iterator<K> iterator() {
    
    return counts.keySet().iterator();
  }
}

class Count {

  private int count;

  public Count() {

    this.count = 0;
  }

  public void add(int count) {

    this.count += count;
  }
  
  public int get() {
    
    return count;
  }
}