开发者

How to copy Key Value Elements from one Hash Table to the other HT

I am trying to copy first 5 key value pair from Hash Table 1 to Hash Table 2 and Then next 开发者_如何学JAVA6 to 10th Key value pair from Hash Table 1 to Hash Table 3.

I am not able to get this going,, can any one has any hint please share it with me


Try something like this.

Hashtable h = new Hashtable();
Hashtable h1 = new Hashtable();
Hashtable h2 = new Hashtable();
Set s = h.keySet();
int i = 0;
for (Object key : s) {
    if ( i++ < 3) {
        h1.put(key, h.get(key));
    } else {
        h2.put(key, h.get(key));
    }
}

Add generics etc. as appropriate.


First of all, you need to know that a Hashtable does not maintain the order in which elements are inserted, so the first 5 can be whatever.

If you want the insertion order to be preserved, use a LinkedHashMap (perhaps wrapping it in a Collections.synchronizedMap() if you want it to be thread-safe).

Besides, there's also a nice interface called NavigableMap, implemented by TreeMap, which offers methods like subMap(), but you need to know from which key to which key (instead of using indices). And this will also hold your entries sorted by the key.

If you can rely only on indices, aside from using a LinkedHashMap, I would suggest you go for a generic solution like the following:

<K, V> Collection<Map<K, V>> splitMap(Map<K, V> map, int count) {
    if (count <= 0) {
        throw new IllegalArgumentException("zero or negative count");
    }
    List<Map<K, V>> list = new ArrayList<Map<K, V>>();
    Iterator<Entry<K, V>> entries = map.entrySet().iterator();
    while (entries.hasNext()) {
        list.add(subMap(entries, count));
    }
    return list;
}

<K, V> Map<K, V> subMap(Iterator<Entry<K, V>> iterator, int count) {
    Map<K, V> map = new LinkedHashMap<K, V>();
    for (int i = 0; i < count && iterator.hasNext(); i++) {
        Entry<K, V> entry = iterator.next();
        map.put(entry.getKey(), entry.getValue());
    }
    return map;
}

Then just call splitMap(yourMap, 5) in order to get the collection (actually a list) of maps containing 5 entries each (or less for the last one if there are not enough entries in the initial map).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜