An utility method used for debugging and printing Map<>. - Java java.util

Java examples for java.util:Map Operation

Description

An utility method used for debugging and printing Map<>.

Demo Code


//package com.java2s;
import java.util.Iterator;

import java.util.Map;
import java.util.Set;

public class Main {
    /**/*from w ww  . j  a v  a  2  s  . c o m*/
     * <p>
     *  An utility method used for debugging and printing. This method gives a String
     *  equivalent of all map values each in a separate line
     * </p>
     * 
     * @param mapToPrint
     *       the map whose values need to be given back a separate entries in each line
     * 
     * @return
     *       the String equivalent of map entries each in a separate line
     */
    public static String getMapEntriesInSeparateLines(
            Map<? extends Object, ? extends Object> mapToPrint) {
        Iterator<? extends Object> iteratorForMap = getIteratorForMap(mapToPrint);

        StringBuilder sb = new StringBuilder();

        Object key = null;

        while (iteratorForMap.hasNext()) {
            key = iteratorForMap.next();

            sb.append(key + "=" + mapToPrint.get(key));
        }

        return sb.toString();
    }

    /**
     * <p>
     * This method returns the <tt>Iterator</tt> of a passed map instance
     * </p>
     * 
     * @param mapObj
     *       A map instance whose iterator needs to be returned
     * 
     * @return
     *       an instance of <tt>Iterator</tt>
     */
    public static Iterator<? extends Object> getIteratorForMap(
            Map<? extends Object, ? extends Object> mapObj) {
        Set<? extends Object> keySet = mapObj.keySet();

        return keySet.iterator();
    }
}

Related Tutorials