Most elegant way to join a Map to a String in Java 8

前端 未结 2 809
萌比男神i
萌比男神i 2020-12-03 10:33

I love Guava, and I\'ll continue to use Guava a lot. But, where it makes sense, I try to use the \"new stuff\" in Java 8 instead.

\"Problem\"

相关标签:
2条回答
  • 2020-12-03 11:02
     public static void main(String[] args) {
    
    
            HashMap<String,Integer> newPhoneBook = new HashMap(){{
                putIfAbsent("Arpan",80186787);
                putIfAbsent("Sanjay",80186788);
                putIfAbsent("Kiran",80186789);
                putIfAbsent("Pranjay",80186790);
                putIfAbsent("Jaiparkash",80186791);
                putIfAbsent("Maya",80186792);
                putIfAbsent("Rythem",80186793);
                putIfAbsent("Preeti",80186794);
    
            }};
    
    
            /**Compining Key and Value pairs and then separate each pair by some delimiter and the add prefix and Suffix*/
            String keyValueCombinedString = newPhoneBook.entrySet().stream().
                    map(entrySet -> entrySet.getKey() + ":"+ entrySet.getValue()).
                    collect(Collectors.joining("," , "[","]"));
            System.out.println(keyValueCombinedString);
    
            /**
             *  OUTPUT : [Kiran:80186789,Arpan:80186787,Pranjay:80186790,Jaiparkash:80186791,Maya:80186792,Sanjay:80186788,Preeti:80186794,Rythem:80186793]
             *
             * */
    
    
            String keyValueCombinedString1 = newPhoneBook.entrySet().stream().
                    map(Objects::toString).
                    collect(Collectors.joining("," , "[","]"));
            System.out.println(keyValueCombinedString1);
    
            /**
             * Objects::toString method concate key and value pairs by =
             * OUTPUT : [Kiran=80186789,Arpan=80186787,Pranjay=80186790,Jaiparkash=80186791,Maya=80186792,Sanjay=80186788,Preeti=80186794,Rythem=80186793]
             * */
    
        }
    
    > Blockquote
    
    0 讨论(0)
  • 2020-12-03 11:04

    You can grab the stream of the map's entry set, then map each entry to the string representation you want, joining them in a single string using Collectors.joining(CharSequence delimiter).

    import static java.util.stream.Collectors.joining;
    
    String s = attributes.entrySet()
                         .stream()
                         .map(e -> e.getKey()+"="+e.getValue())
                         .collect(joining("&"));
    

    But since the entry's toString() already output its content in the format key=value, you can call its toString method directly:

    String s = attributes.entrySet()
                         .stream()
                         .map(Object::toString)
                         .collect(joining("&"));
    
    0 讨论(0)
提交回复
热议问题