Created
December 7, 2013 06:33
-
-
Save kunst1080/7837966 to your computer and use it in GitHub Desktop.
Generic List/Map Literal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package literal; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class L { | |
private L(){} | |
public static <T> ListBuilder<T> add(T e) { | |
ListBuilder<T> listBuilder = new ListBuilder<T>(); | |
return listBuilder.add(e); | |
} | |
public static class ListBuilder<T> { | |
private ListBuilder(){}; | |
private List<T> list = new ArrayList<T>(); | |
public ListBuilder<T> add(T e) { | |
list.add(e); | |
return this; | |
} | |
public List<T> end() { | |
return list; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package literal; | |
import java.util.LinkedHashMap; | |
import java.util.Map; | |
public class M { | |
private M(){} | |
public static <K, V> MapBuilder<K, V> put(K key, V value) { | |
MapBuilder<K, V> mapBuilder = new MapBuilder<K, V>(); | |
return mapBuilder.put(key, value); | |
} | |
public static class MapBuilder<K, V> { | |
private MapBuilder(){}; | |
private Map<K, V> map = new LinkedHashMap<K, V>(); | |
public MapBuilder<K, V> put(K key, V value) { | |
map.put(key, value); | |
return this; | |
} | |
public Map<K, V> end() { | |
return map; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package literal; | |
import static org.junit.Assert.assertEquals; | |
import java.util.List; | |
import java.util.Map; | |
import org.junit.Test; | |
public class LiteralTest { | |
@Test | |
public void mapTest() { | |
Map<String,String> h = literal.M | |
.put("1", "fugafuga") | |
.put("2", "aaaa") | |
.end(); | |
assertEquals("fugafuga", h.get("1")); | |
assertEquals("aaaa", h.get("2")); | |
} | |
@Test | |
public void listTest() { | |
List<String> l = literal.L | |
.add("1") | |
.add("fuga") | |
.add("aa") | |
.end(); | |
assertEquals("1", l.get(0)); | |
assertEquals("fuga", l.get(1)); | |
assertEquals("aa", l.get(2)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment