RFC: draft API for JEP 269 Convenience Collection Factories (original) (raw)

Ivan Gerasimov ivan.gerasimov at oracle.com
Wed Oct 14 12:56:28 UTC 2015


Hi Stuart!

Most of the API is pretty straightforward, with fixed-arg and varargs "of()" factories for List, Set, ArrayList, and HashSet; and with fixed-arg "of()" factories and varargs "ofEntries()" factories for Map and HashMap.

Has it been considered to separate a Map creation into two steps: specifying keys and then values? Varargs methods can then be used in each step.

I understand, that keeping the key and the value close each other looks better in many cases. However, separating them can allow some additional flexibility.

Here's a draft of what it might look like:


import java.util.; import java.util.function.;

public class MapOf {

 public static void main(String[] a) {
     Map<Integer,Character> m1 = MyCollections.<Integer,Character>
              ofKeys( 1,   2,   3,   4,   5)
             .vals(  'a', 'b', 'c', 'd', 'e');
     m1.forEach((k, v) -> System.out.println("m1[" + k + "] = " + v));

     Map<Integer,String> m2 = MyCollections.<Integer,String>
              ofKeys( 1,   2,   3,   4,   5)
             .calculateVals(k -> "#" + k + "#");
     m2.forEach((k, v) -> System.out.println("m2[" + k + "] = " + v));
 }

}

class MyCollections { public static <K,V> KeysHolder<K,V> ofKeys(K... keys) { return new KeysHolder<>(keys); }

 public static class KeysHolder<K,V> {
     K[] keys;
     KeysHolder(K[] keys) {
         this.keys = keys;
     }

     public Map<K,V> vals(V... vals) {
         if (vals.length != keys.length) {
             throw new IllegalArgumentException();
         }

         Map<K,V> result = new HashMap<>();
         for (int i = 0; i < keys.length; ++i) {
             result.put(keys[i], vals[i]);
         }
         return result;
     }

     public Map<K,V> calculateVals(Function<K,V> fun) {
         Map<K,V> result = new HashMap<>();
         for (int i = 0; i < keys.length; ++i) {
             result.put(keys[i], fun.apply(keys[i]));
         }
         return result;
     }
 }

}

Sincerely yours, Ivan



More information about the core-libs-dev mailing list