简体   繁体   中英

java iterate over map except last iteration

I have the next map values :

{title=varchar(50), text=text}

I am trying to convert it into two strings like this:

StringBuffer string = new StringBuffer();
for (String keyinside: values.keySet()) {
    string.append(keyinside + " " + values.get(keyinside) + ", ");
}

But what I want here - not inlude ", " at the last iteration. How can I do it?

Short java 8 alternative:

String result = values.entrySet().stream().map(e -> e.getKey() + " " + e.getValue())
                         .collect(Collectors.joining(", "))

Stream.map() to convert all entries in the map to a string description of the entry.

Note that Java 8 also finally adds the function String.join() .

Use some indicator :

StringBuffer string = new StringBuffer();
boolean first = true;
for (String keyinside: values.keySet()) {
    if (!first)
        string.append (", ");
    else
        first = false;
    string.append(keyinside + " " + values.get(keyinside));
}

BTW, it's more efficient to use StringBuilder (assuming you don't need thread safety).

Take a counter which increments in every iteration and get a if condition which checks whether it is iterating the last time

A simple trick is

        int i = 0 ;
        for (String keyinside: values.keySet()) {
            string.append(keyinside + " " + values.get(keyinside));
            if((i+1)<values.keySet().size()){
                string.append(", ");
            }
            i++;
        }

Also I suggest you to use StringBuilder if thread safety is not a concern

I quite like Joiner from Google collections library. You could just do this:

on(",").withKeyValueSeparator(" ").join(values);

on is statically imported from com.google.common.base.Joiner .

If you use Maven, just add a dependency:

<dependency>
    <groupId>com.google.collections</groupId>
    <artifactId>google-collections</artifactId>
    <version>1.0</version>
</dependency>

You can try this .by which we can remove the comma(,) at end. Hope this helps you.

    Map<String,String> s= new LinkedHashMap<String,String>();
    s.put("1", "A");
    s.put("2", "B");
    s.put("3", "C");
    StringBuffer sb = new StringBuffer();
    String ans=null;
    for (String keyinside: s.keySet()) {
         sb.append(keyinside + " " + s.get(keyinside) + ", ").toString();
    } 
    System.out.println(sb);
    ans=sb.substring(0, sb.length()-2).toString();
    System.out.println(ans);

Note: you can refer How to remove the last character from a string?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM