Java-Gaming.org Hi !
Featured games (90)
games approved by the League of Dukes
Games in Showcase (777)
Games in Android Showcase (231)
games submitted by our members
Games in WIP (856)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Map builder  (Read 3740 times)
0 Members and 1 Guest are viewing this topic.
Offline ags1

JGO Kernel


Medals: 367
Projects: 7


Make code not war!


« Posted 2014-09-05 10:44:02 »

I seem to build a lot of maps, and I hate the multi-line verbosity. So I made a map builder to turn mapping into a one-liner affair.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
package org.example.misc;

import java.util.HashMap;
import java.util.Map;

public class Maps {

    public static <Q,W> MapWrapper<Q,W> map(Q q, W w) {
        return new MapWrapper<Q, W>(q, w);
    }

    public static final class MapWrapper<Q,W> {
        private final HashMap<Q,W> map;
        public MapWrapper(Q q, W w) {
            map = new HashMap<Q, W>();
            map.put(q, w);
        }
        public MapWrapper<Q,W> map(Q q, W w) {
            map.put(q, w);
            return this;
        }
        public Map<Q,W> getMap() {
            return map;
        }
    }

    public static void main(String[] args) {
        Map<String, Integer> map = Maps.map("one", 1).map("two", 2).map("three", 3).getMap();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

Offline theagentd
« Reply #1 - Posted 2014-09-05 12:02:27 »

Even less code by extending HashMap!

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
package org.example.misc;

import java.util.HashMap;
import java.util.Map;

public class Maps {

    public static <Q,W> MyHashMap<Q,W> map(Q q, W w) {
        return new MyHashMap<Q, W>(q, w);
    }

    public static final class MyHashMap<Q, W> extends HashMap<Q, W>{

        public MyHashMap(Q q, W w) {
            put(q, w);
        }

        public MyHashMap<Q,W> map(Q q, W w) {
            put(q, w);
            return this;
        }
    }

    public static void main(String[] args) {
        Map<String, Integer> map = Maps.map("one", 1).map("two", 2).map("three", 3);
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

Myomyomyo.
Offline BurntPizza

« JGO Bitwise Duke »


Medals: 486
Exp: 7 years



« Reply #2 - Posted 2014-09-05 13:21:29 »

Not the most type safe thing I've written, but here it is interleaved:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
import java.util.HashMap;
import java.util.Map;

public class Maps {
   
   @SuppressWarnings("unchecked")
   public static <K, V> Map<K, V> map(Object... a) {
      if (a.length % 2 != 0)
         throw new IllegalArgumentException("Keys and Values must be in pairs");
     
      Map<K, V> map = new HashMap<>();
     
      for (int i = 0; i < a.length;)
         map.put((K) a[i++], (V) a[i++]);
     
      return map;
   }
   
   public static void main(String[] a) {
      Map<String, Integer> map = Maps.map("one", 1, "two", 2, "three", 3);
     
      for (Map.Entry<String, Integer> entry : map.entrySet())
         System.out.println(entry.getKey() + " = " + entry.getValue());
     
   }
}


Little more verbose to call map(), but at least it will throw an error on wrongly typed args:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
import java.util.HashMap;
import java.util.Map;

public class Maps {
   
   @SuppressWarnings("unchecked")
   public static <K, V> Map<K, V> map(Class<K> kc, Class<V> vc, Object... a) {
      if (a.length % 2 != 0)
         throw new IllegalArgumentException("Keys and Values must be in pairs");
     
      Map<K, V> map = new HashMap<>();
     
      for (int i = 0; i < a.length;) {
         Object k = a[i++], v = a[i++];
         if (!kc.isInstance(k))
            throw new IllegalArgumentException("Wrong typed argument: " + k);
         if (!vc.isInstance(v))
            throw new IllegalArgumentException("Wrong typed argument: " + v);
         map.put((K) k, (V) v);
      }
     
      return map;
   }
   
   public static void main(String[] a) {
      Map<String, Integer> map = Maps.map(String.class, Integer.class, "one", 1, "two", 2, "three", 3);
     
      for (Map.Entry<String, Integer> entry : map.entrySet())
         System.out.println(entry.getKey() + " = " + entry.getValue());
     
   }
}
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline StrideColossus
« Reply #3 - Posted 2014-09-05 15:07:27 »

Another approach using the little-known double-brace initialization technique:

<code>
   private final Map<String, Integer> map = new HashMap<String, Integer>() {{
      put( "one", 1 );
      put( "two", 2 );
   }};
</code>

Slightly more verbose in that you have to replicate the key/value classes since the created map is actually an anonymous class.
Offline BurntPizza

« JGO Bitwise Duke »


Medals: 486
Exp: 7 years



« Reply #4 - Posted 2014-09-05 15:13:04 »

Doesn't really save much, plus it's not 1 line, and it creates anonymous class. I try to avoid double-brace.
Offline ags1

JGO Kernel


Medals: 367
Projects: 7


Make code not war!


« Reply #5 - Posted 2014-09-05 17:22:07 »

Even less code by extending HashMap!


I've read that extending the collections classes is bad practice...? But sometimes I want to build different maps like TreeMaps so I prefer not to extend but wrap instead. Then I could do something like:

1  
 Maps.treeMap("one", 1).map(...).getMap(); 

Pages: [1]
  ignore  |  Print  
 
 

 
hadezbladez (335 views)
2018-11-16 13:46:03

hadezbladez (180 views)
2018-11-16 13:41:33

hadezbladez (336 views)
2018-11-16 13:35:35

hadezbladez (83 views)
2018-11-16 13:32:03

EgonOlsen (2177 views)
2018-06-10 19:43:48

EgonOlsen (2205 views)
2018-06-10 19:43:44

EgonOlsen (1378 views)
2018-06-10 19:43:20

DesertCoockie (2009 views)
2018-05-13 18:23:11

nelsongames (1651 views)
2018-04-24 18:15:36

nelsongames (2299 views)
2018-04-24 18:14:32
Deployment and Packaging
by mudlee
2018-08-22 18:09:50

Java Gaming Resources
by gouessej
2018-08-22 08:19:41

Deployment and Packaging
by gouessej
2018-08-22 08:04:08

Deployment and Packaging
by gouessej
2018-08-22 08:03:45

Deployment and Packaging
by philfrei
2018-08-20 02:33:38

Deployment and Packaging
by philfrei
2018-08-20 02:29:55

Deployment and Packaging
by philfrei
2018-08-19 23:56:20

Deployment and Packaging
by philfrei
2018-08-19 23:54:46
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!