construct Query String from Map - Java java.util

Java examples for java.util:Map Creation

Description

construct Query String from Map

Demo Code


//package com.book2s;

import java.util.Iterator;

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

public class Main {
    public static String constructQueryString(
            final Map<String, String> query) {

        final Set<Map.Entry<String, String>> mapEntries = query.entrySet();
        final Iterator<Map.Entry<String, String>> iterator = mapEntries
                .iterator();//from  w w  w .j a  v a 2s . c  o  m
        final StringBuilder queryStringBuilder = new StringBuilder();

        while (iterator.hasNext()) {
            final Map.Entry<String, String> entry = iterator.next();
            final String pair = String.format("%s=%s", entry.getKey(),
                    entry.getValue());

            queryStringBuilder.append(pair);
            if (iterator.hasNext()) {
                queryStringBuilder.append('&');
            }

        }

        return queryStringBuilder.toString();
    }
}

Related Tutorials