Last active
August 29, 2015 14:05
-
-
Save Falci/41732c3c61295d504cca to your computer and use it in GitHub Desktop.
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 me.falci.util; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Map.Entry; | |
import com.google.common.base.Function; | |
import com.google.common.base.Joiner; | |
import com.google.common.collect.Lists; | |
public class MapUtil { | |
public static String toString(Map<String, String> map, String joiner, Function<Entry<String, String>, String> function){ | |
List<String> transformed = Lists.transform(Lists.newArrayList(map.entrySet()), function); | |
return Joiner.on(joiner).join(Lists.newArrayList(transformed)); | |
} | |
public static String serialize(Map<String, String> map){ | |
return toString(map, "&", new Function<Entry<String, String>, String>() { | |
@Override | |
public String apply(Entry<String, String> item) { | |
return item.getKey() + "=" + item.getValue(); | |
} | |
}); | |
} | |
} |
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 me.falci.util; | |
import java.util.HashMap; | |
import java.util.Map; | |
import junit.framework.Assert; | |
public class MapUtilTest { | |
@Test | |
public void test() { | |
Map<String, String> map = new HashMap<>(3); | |
map.put("key1", "value1"); | |
map.put("key2", "value2"); | |
map.put("key3", "value3"); | |
String serialized = MapUtil.serialize(map); | |
Assert.assertTrue(serialized.contains("key1=value1")); | |
Assert.assertTrue(serialized.contains("key2=value2")); | |
Assert.assertTrue(serialized.contains("key3=value3")); | |
Assert.assertEquals(3, serialized.split("&").length); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment