How to convert map to url query string?

前端 未结 17 1533
盖世英雄少女心
盖世英雄少女心 2020-11-27 13:39

Do you know of any utility class/library, that can convert Map into URL-friendly query string?

Example:

I have a map:

\"param1\"=12,
\"param2         


        
17条回答
  •  -上瘾入骨i
    2020-11-27 14:17

    I wanted to build on @eclipse's answer using java 8 mapping and reducing.

     protected String formatQueryParams(Map params) {
          return params.entrySet().stream()
              .map(p -> p.getKey() + "=" + p.getValue())
              .reduce((p1, p2) -> p1 + "&" + p2)
              .map(s -> "?" + s)
              .orElse("");
      }
    

    The extra map operation takes the reduced string and puts a ? in front only if the string exists.

提交回复
热议问题