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-2011 the original author or authors. 014 */ 015 package org.fest.util; 016 017 import static org.fest.util.ToString.toStringOf; 018 019 import java.util.*; 020 import java.util.Map.Entry; 021 022 /** 023 * Utility methods related to maps. 024 * 025 * @author Yvonne Wang 026 * @author Alex Ruiz 027 */ 028 public class Maps { 029 030 /** 031 * Returns {@code true} if the given map is {@code null} or empty. 032 * @param map the map to check. 033 * @return {@code true} if the given map is {@code null} or empty, otherwise {@code false}. 034 */ 035 public static boolean isEmpty(Map<?, ?> map) { 036 return map == null || map.isEmpty(); 037 } 038 039 /** 040 * Returns the {@code String} representation of the given map, or {@code null} if the given map is {@code null}. 041 * @param map the map to format. 042 * @return the {@code String} representation of the given map. 043 */ 044 public static String format(Map<?, ?> map) { 045 if (map == null) return null; 046 Iterator<?> i = map.entrySet().iterator(); 047 if (!i.hasNext()) return "{}"; 048 StringBuilder b = new StringBuilder(); 049 b.append("{"); 050 for (;;) { 051 Entry<?, ?> e = (Entry<?, ?>) i.next(); 052 b.append(format(map, e.getKey())); 053 b.append('='); 054 b.append(format(map, e.getValue())); 055 if (!i.hasNext()) return b.append("}").toString(); 056 b.append(", "); 057 } 058 } 059 060 private static Object format(Map<?, ?> map, Object o) { 061 return o == map ? "(this Map)" : toStringOf(o); 062 } 063 064 private Maps() {} 065 }