Java-Gaming.org Hi !
Featured games (91)
games approved by the League of Dukes
Games in Showcase (757)
Games in Android Showcase (229)
games submitted by our members
Games in WIP (844)
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 3482 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: 485
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: 485
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  
 
 

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

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

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

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

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

nelsongames (154 views)
2018-04-24 18:14:32

ivj94 (895 views)
2018-03-24 14:47:39

ivj94 (156 views)
2018-03-24 14:46:31

ivj94 (808 views)
2018-03-24 14:43:53

Solater (172 views)
2018-03-17 05:04:08
Java Gaming Resources
by philfrei
2017-12-05 19:38:37

Java Gaming Resources
by philfrei
2017-12-05 19:37:39

Java Gaming Resources
by philfrei
2017-12-05 19:36:10

Java Gaming Resources
by philfrei
2017-12-05 19:33:10

List of Learning Resources
by elect
2017-03-13 14:05:44

List of Learning Resources
by elect
2017-03-13 14:04:45

SF/X Libraries
by philfrei
2017-03-02 08:45:19

SF/X Libraries
by philfrei
2017-03-02 08:44:05
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!