Created
November 20, 2012 01:59
-
-
Save monzou/4115480 to your computer and use it in GitHub Desktop.
guava misc
This file contains hidden or 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 sandbox; | |
| import java.util.Collections; | |
| import java.util.Comparator; | |
| import java.util.List; | |
| import java.util.Map; | |
| import com.google.common.base.Joiner; | |
| import com.google.common.collect.Lists; | |
| import com.google.common.collect.Maps; | |
| import com.google.common.collect.Ordering; | |
| /** | |
| * GuavaMisc | |
| * | |
| * @author monzou | |
| */ | |
| public class GuavaMisc { | |
| public static void main(String[] args) { | |
| // Joiner | |
| { | |
| Map<Integer, String> map = Maps.newLinkedHashMap(); | |
| map.put(1, "foo"); | |
| map.put(2, "bar"); | |
| map.put(3, null); | |
| System.out.println(Joiner.on("&").useForNull("null").withKeyValueSeparator("=").join(map)); // 1=foo&2=bar&3=null | |
| } | |
| // Ordering | |
| { | |
| List<ValueModel<Integer>> values = Lists.newArrayList(); | |
| values.add(new ValueModel<Integer>(2)); | |
| values.add(new ValueModel<Integer>(3)); | |
| values.add(new ValueModel<Integer>(null)); | |
| values.add(new ValueModel<Integer>(1)); | |
| values.add(null); | |
| System.out.println(Joiner.on(", ").useForNull("null").join(values)); // 2, 3, null-value, 1, null | |
| Comparator<ValueModel<Integer>> comparator = Ordering.from(new Comparator<ValueModel<Integer>>() { | |
| final Comparator<Integer> valueComparator = Ordering.natural().nullsFirst(); | |
| /** {@inheritDoc} */ | |
| @Override | |
| public int compare(ValueModel<Integer> o1, ValueModel<Integer> o2) { | |
| return valueComparator.compare(o1.value, o2.value); | |
| } | |
| }).nullsFirst(); | |
| Collections.sort(values, comparator); | |
| System.out.println(Joiner.on(", ").useForNull("null").join(values)); // null, null-value, 1, 2, 3 | |
| } | |
| } | |
| private static class ValueModel<T> { | |
| T value; | |
| ValueModel(T value) { | |
| this.value = value; | |
| } | |
| /** {@inheritDoc} */ | |
| @Override | |
| public String toString() { | |
| return value == null ? "null-value" : value.toString(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment