Map to string conversion in java

How to convert a map to a string in Java

In this tutorial, we will learn how to convert a map to a string in Java. In Java, map is a collection where every map element contains key pairs. It means every key has one value associated with it. Duplicates can’t be there as every key has its unique pair. In Java, list is also a collection for storing the references of every element sequentially as every element can be uniquely identified because of its index.

There are many ways in which we can convert a map to a string. The two ways are:

Ways to Convert a map to a string in Java

We have explained each of the methods one by one with example.

Using two lists

We can convert a map to a string in java using two array lists. In this, we first fill the map with the keys. Then, we will use keySet() method for returning the keys in the map, and values() method for returning the value present in the map to the ArrayList constructor parameter.

Like this way:

List k_list = new ArrayList(mp.keySet()); List v_List = new ArrayList(mp.values());
import java.util.*; public class Main < public static void main(String[] args) < Scanner in = new Scanner(System.in); String m; int n; System.out.println("enter the number of inputs"); n=in.nextInt(); System.out.println("enter the strings"); m=in.nextLine(); Mapmp = new HashMap<>(); for(int i=1;i <=n;i++) < m=in.nextLine(); mp.put(i,m); >List k_List = new ArrayList(mp.keySet()); List v_List = new ArrayList(mp.values()); System.out.println("Key List: " + k_List); System.out.println("Value List: " + v_List); > >
Enter the number of inputs 5 Enter the strings red blue green black orange Key List: [1, 2, 3, 4, 5] Value List: [red, blue, green, black, orange]

2) Using stream:

We can also convert a map to a string in java by using streams by including the package import java.util.stream.Collectors consisting of stream() method, collect() method, etc for the conversion. We will provide the values in the maps and the associated keys are generated. Here, keySet() return the keys and values() return values from the map to the List using stream() method. The collect() method collects the streams of the returned value and converts them into the list passing Collectors.toList() in the parameter.

List k_List = mp.keySet().stream().collect(Collectors.toList()); List v_List = mp.values().stream().collect(Collectors.toList());
import java.util.*; import java.util.stream.Collectors; public class Main < public static void main(String[] args) < Scanner in = new Scanner(System.in); String m; int n; System.out.println("Enter the number of inputs"); n=in.nextInt(); System.out.println("Enter the strings"); m=in.nextLine(); Mapmap = new HashMap<>(); for(int i=1;i <=n;i++) < m=in.nextLine(); mp.put(i,m); >List k_List = mp.keySet().stream().collect(Collectors.toList()); List v_List = mp.values().stream().collect(Collectors.toList()); System.out.println("Key List: " + k_List); System.out.println("Value List: " + v_List); > >
Enter the number of inputs 5 Enter the strings violet indigo blue green yellow Key List: [1, 2, 3, 4, 5] Value List: [violet, indigo, blue, green, yellow]

Hope this tutorial was useful.

Читайте также:  Create temporary table mysql php

Источник

Преобразование Map в String в Java

В этом руководстве мы сосредоточимся на преобразовании карты в строку и наоборот.

Сначала мы увидим, как добиться этого с помощью основных методов Java, а затем воспользуемся некоторыми сторонними библиотеками.

2. Пример основной карты ​

Во всех примерах мы будем использовать одну и ту же реализацию Map :

 MapInteger, String> wordsByKey = new HashMap>();  wordsByKey.put(1, "one");  wordsByKey.put(2, "two");  wordsByKey.put(3, "three");  wordsByKey.put(4, "four"); 

3. Преобразование карты в строку путем итерации​

Давайте переберем все ключи в нашей карте и для каждого из них добавим комбинацию ключ-значение к нашему результирующему объекту StringBuilder .

Для целей форматирования мы можем заключить результат в фигурные скобки:

 public String convertWithIteration(MapInteger, ?> map)    StringBuilder mapAsString = new StringBuilder(");   for (Integer key : map.keySet())    mapAsString.append(key + "=" + map.get(key) + ", ");   >   mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append(">");   return mapAsString.toString();   > 

Чтобы проверить, правильно ли мы преобразовали нашу карту , давайте запустим следующий тест:

 @Test   public void givenMap_WhenUsingIteration_ThenResultingStringIsCorrect()    String mapAsString = MapToString.convertWithIteration(wordsByKey);   Assert.assertEquals("", mapAsString);   > 

4. Преобразование карты в строку с использованием потоков Java .​

Чтобы выполнить преобразование с использованием потоков, нам сначала нужно создать поток из доступных ключей Map .

Во-вторых, мы сопоставляем каждый ключ с удобочитаемой строкой .

Наконец, мы объединяем эти значения и для удобства добавляем некоторые правила форматирования с помощью метода Collectors.joining() :

 public String convertWithStream(MapInteger, ?> map)    String mapAsString = map.keySet().stream()   .map(key -> key + "=" + map.get(key))   .collect(Collectors.joining(", ", ", ">"));   return mapAsString;   > 

5. Преобразование карты в строку с помощью гуавы​

Давайте добавим Guava в наш проект и посмотрим, как мы можем добиться преобразования в одной строке кода:

 dependency>   groupId>com.google.guavagroupId>   artifactId>guavaartifactId>   version>31.0.1-jreversion>   dependency> 

Чтобы выполнить преобразование с использованием класса Joiner в Guava , нам нужно определить разделитель между различными записями карты и разделитель между ключами и значениями:

 public String convertWithGuava(MapInteger, ?> map)    return Joiner.on(",").withKeyValueSeparator("=").join(map);   > 

6. Преобразование карты в строку с помощью Apache Commons​

Чтобы использовать Apache Commons , давайте сначала добавим следующую зависимость:

 dependency>   groupId>org.apache.commonsgroupId>   artifactId>commons-collections4artifactId>   version>4.2version>   dependency> 

Соединение очень простое — нам просто нужно вызвать метод StringUtils.join :

 public String convertWithApache(Map map)    return StringUtils.join(map);   > 

Отдельного упоминания заслуживает метод debugPrint , доступный в Apache Commons. Это очень полезно для целей отладки.

 MapUtils.debugPrint(System.out, "Map as String", wordsByKey); 

отладочный текст будет записан в консоль:

 Map as String =      1 = one java.lang.String  2 = two java.lang.String  3 = three java.lang.String  4 = four java.lang.String  > java.util.HashMap 

7. Преобразование строки в карту с использованием потоков​

Чтобы выполнить преобразование из String в Map , давайте определим, где разбивать и как извлекать ключи и значения:

 public MapString, String> convertWithStream(String mapAsString)    MapString, String> map = Arrays.stream(mapAsString.split(","))   .map(entry -> entry.split("="))   .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));   return map;   > 

8. Преобразование строки в карту с помощью гуавы​

Более компактная версия вышеизложенного состоит в том, чтобы полагаться на Guava, который выполняет разделение и преобразование для нас в однострочном процессе:

 public MapString, String> convertWithGuava(String mapAsString)    return Splitter.on(',').withKeyValueSeparator('=').split(mapAsString);   > 

9. Заключение​

В этой статье мы увидели, как преобразовать карту в строку и наоборот, используя как основные методы Java, так и сторонние библиотеки.

Реализацию всех этих примеров можно найти на GitHub .

Источник

Map to String Conversion in Java

VietMX's Blog

In this tutorial, we’ll focus on conversion from a Map to a String and the other way around.

First, we’ll see how to achieve these using core Java methods, and afterward, we’ll use some third-party libraries.

2. Basic Map Example

In all examples, we’re going to use the same Map implementation:

Map wordsByKey = new HashMap<>(); wordsByKey.put(1, "one"); wordsByKey.put(2, "two"); wordsByKey.put(3, "three"); wordsByKey.put(4, "four");

3. Convert a Map to a String by Iterating

Let’s iterate over all the keys in our Map and, for each of them, append the key-value combination to our resulting StringBuilder object.

For formatting purposes, we can wrap the result in curly brackets:

public String convertWithIteration(Map map) < StringBuilder mapAsString = new StringBuilder("<"); for (Integer key : map.keySet()) < mapAsString.append(key + "=" + map.get(key) + ", "); >mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append(">"); return mapAsString.toString(); >

To check if we converted our Map correctly, let’s run the following test:

@Test public void givenMap_WhenUsingIteration_ThenResultingStringIsCorrect() < String mapAsString = MapToString.convertWithIteration(wordsByKey); Assert.assertEquals("", mapAsString); >

4. Convert a Map to a String Using Java Streams

To perform conversion using streams, we first need to create a stream out of the available Map keys.

Secondly, we’re mapping each key to a human-readable String.

Finally, we’re joining those values, and, for the sake of convenience, we’re adding some formatting rules using the Collectors.joining() method:

public String convertWithStream(Map map) < String mapAsString = map.keySet().stream() .map(key ->key + "=" + map.get(key)) .collect(Collectors.joining(", ", "")); return mapAsString; >

5. Convert a Map to a String Using Guava

Let’s add Guava into our project and see how we can achieve the conversion in a single line of code:

 com.google.guava guava 27.0.1-jre  

To perform the conversion using Guava’s Joiner class, we need to define a separator between different Map entries and a separator between keys and values:

public String convertWithGuava(Map map)

6. Convert a Map to a String Using Apache Commons

To use Apache Commons, let’s add the following dependency first:

 org.apache.commons commons-collections4 4.2  

The joining is very straightforward – we just need to call the StringUtils.join method:

public String convertWithApache(Map map)

One special mention goes to the debugPrint method available in Apache Commons. It is very useful for debugging purposes.

MapUtils.debugPrint(System.out, "Map as String", wordsByKey);

The debug text will be written to the console:

Map as String = < 1 = one java.lang.String 2 = two java.lang.String 3 = three java.lang.String 4 = four java.lang.String >java.util.HashMap

7. Convert a String to a Map Using Streams

To perform conversion from a String to a Map, let’s define where to split on and how to extract keys and values:

public Map convertWithStream(String mapAsString) < Mapmap = Arrays.stream(mapAsString.split(",")) .map(entry -> entry.split("=")) .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1])); return map; >

8. Convert a String to a Map Using Guava

A more compact version of the above is to rely on Guava to do the splitting and conversion for us in a one-line process:

public Map convertWithGuava(String mapAsString)

9. Conclusion

In this tutorial, we saw how to convert a Map to a String and the other way around using both core Java methods and third-party libraries.

The implementation of all of these examples can be found over on GitHub.

Источник

Оцените статью