0

I have a parameter map and I am trying to build the complete url by appending the request parameters to the url.

Following code is what I have done so far to extract key values from the parameter map.

Map<String, String[]> parameters = request.getParameterMap();

String params = parameters.entrySet()
                .stream()
                .map(e -> e.getKey() + "=" + String.join(",", e.getValue()))
                .collect(Collectors.joining("&"));
String url = requestUrl + "?" + params;

My url currently prints something similar to following if I pass value only to the year parameter:

/student/query?Id=&grade=&year=2018

I want to print something like:

/student/query?year=2018

If I do not pass value for a certain parameter I do not want it to be printed.

How can I fix this?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
BlueStar
  • 401
  • 3
  • 9
  • 29
  • You should [encode](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/URLEncoder.html#encode(java.lang.String,java.lang.String)) each key and value. – VGR Sep 28 '18 at 14:50

1 Answers1

2

You can use filter which only keeps String[] that contains non-empty strings:

            .filter(e -> {
                String[] value = e.getValue();
                if (value == null || value.length == 0) {
                    return false;
                } else {
                    for (String element : value) {
                        if (element != null && !element.isEmpty()) {
                            return true;
                        }
                    }
                    return false;
                }
            })
xingbin
  • 27,410
  • 9
  • 53
  • 103