001 /*
002 * Created on Jan 25, 2008
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
005 * the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
010 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
011 * specific language governing permissions and limitations under the License.
012 *
013 * Copyright @2008 the original author or authors.
014 */
015 package org.fest.util;
016
017 import static org.fest.util.Strings.quote;
018
019 import java.util.Iterator;
020 import java.util.Map;
021 import java.util.Map.Entry;
022
023 /**
024 * Understands utility methods related to maps.
025 *
026 * @author Yvonne Wang
027 * @author Alex Ruiz
028 */
029 public class Maps {
030
031 /**
032 * Returns <code>true</code> if the given map is <code>null</code> or empty.
033 * @param map the map to check.
034 * @return <code>true</code> if the given map is <code>null</code> or empty, otherwise <code>false</code>.
035 */
036 public static boolean isEmpty(Map<?, ?> map) {
037 return map == null || map.isEmpty();
038 }
039
040 /**
041 * Returns the <code>String</code> representation of the given map, or <code>null</code> if the given map is
042 * <code>null</code>.
043 * @param map the map to format.
044 * @return the <code>String</code> representation of the given map.
045 */
046 public static String format(Map<?, ?> map) {
047 if (map == null) return null;
048 Iterator<?> i = map.entrySet().iterator();
049 if (!i.hasNext()) return "{}";
050 StringBuilder b = new StringBuilder();
051 b.append("{");
052 for (;;) {
053 Entry<?, ?> e = (Entry<?, ?>)i.next();
054 b.append(format(map, e.getKey()));
055 b.append('=');
056 b.append(format(map, e.getValue()));
057 if (!i.hasNext()) return b.append("}").toString();
058 b.append(", ");
059 }
060 }
061
062 private static Object format(Map<?, ?> map, Object o) {
063 return o == map ? "(this Map)" : quote(o);
064 }
065
066 private Maps() {}
067 }