-1

I need a key-value pair and I need to iterate over it, but I need to remove the & from the last iteration.

My key-value Map object is defined as:

private Map<String, String> additionalAttributes = new HashMap<String,String>();

I perform my iteration as such:

for(Entry<String,String> i : additionalAttributes.entrySet()) {
    attributes += i.getKey() + "=" +i.getValue() + "&";
}

Is there any way I can determine if the current entry i is the last entry in the map? The map will vary in size and contents each time it's run so I need a dynamic solution.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
CS2020
  • 153
  • 1
  • 10
  • 2
    Just remove the trailing "&" when you've finished iterating. – Steve Smith Jun 02 '17 at 15:57
  • 1
    This is why concise questions get better answers :) – Alfabravo Jun 02 '17 at 16:01
  • 1
    The question is closed, so you're literal question will never get a direct answer. If your problem is that you genuinely need knowledge of the "last item", and the example you gave is deceptive, then you need to dig into the API. The entrySet() call returns an Iterator (that's what you are iterating over). Iterator has a function call "hasNext()" which returns true if there are more items, and false when you're at the last item. This is how one can determine that - although it's doubtful if you need the literal answer in this case. :) (edit wrong 'your') – Chris Parker Jun 02 '17 at 16:15

1 Answers1

4

It may be much easier to let Java's streams do the heavy lifting for you:

String attributes = 
    additionalAttributes.entrySet()
                        .stream()
                        .map(e -> e.getKey() + "=" + e.getValue())
                        .collect(Collectors.joining("&"));
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 2
    This does not address OP's request of determining the last item of the iteration – lucasvw Jun 02 '17 at 15:57
  • 1
    This is the [XY Problem](https://meta.stackexchange.com/a/66378/223467). It answers the actual need, not the implementation detail of determining the last item in the entry set. – Mureinik Jun 02 '17 at 15:58