开发者

Putting placeholders in a key/value List based on a Set of keys in Java

开发者_StackOverflow中文版

I have a Set of keys and a List of key/value pairs. The values are of the form Long,BigInteger.

// key/values pairs: Long,BigInteger
List<Object[]> values;
// id list that corresponds to the keys for the list above
Set<Long> ids;

If any member of the key Set does not exist as a key in the key/value list, I want to add it to the list with a value of 0.

What's a good way to do this in Java?


The various commenters suggesting maps make a good point. How about instead of

List<Object[]> values 

you use

Map<Long, BigInteger> values

In that case:

for(Long id : ids) {
    if(!values.containsKey(id)) {
        values.put(id, BigInteger.ZERO);
    }
}

In fact, even if the code as must be kept as written I'd consider using a map for manipulation by pre-processing the list into a map, then dumping it back into the list of object arrays.


What's a good way to do this in Java?

Replace the Set<Long> and List<Object[]> by a Map<Long, BigInteger>. If the ordering is not important, then use HashMap. If you'd like to sort automagically on keys, then use TreeMap. If you'd like to maintain insertion order, then use LinkedHashMap.

E.g.

Map<Long, BigInteger> unorderedMap = new HashMap<Long, BigInteger>();
Map<Long, BigInteger> orderedByKeys = new TreeMap<Long, BigInteger>();
Map<Long, BigInteger> orderedByInsertion = new LinkedHashMap<Long, BigInteger>();

This way you can just use any of the Map methods to handle key/value pairs. E.g.

Long key = 1L;
BigInteger value = map.get(key);
if (value == null) {
    value = new BigInteger(0);
    map.put(key, value);
}

You can even get all keys by Map#keySet():

Set<Long> keys = map.keySet();

To learn more about maps, consult Sun's own tutorial about the subject.


I think you want to use something like one of the Google Collections Multimap implementations. Don't re-invent the wheel. The Apache Commons has something similar I suspect, but I prefer the Google library.

Querying for a key that has no values returns an empty collection.

EDIT: options for sorting order, uniqueness, etc are all available, just pick the right implementation according to your requirements.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜