here is the sample code for saving key-values with hashmap :

HashMap<String, String> data = new HashMap<String, String>();
data.put("key", "value");

or if the order matters to you use linkedHashMap :

HashMap<String, String> data = new LinkedHashMap<>();

the usage is the same;)

Answer from SepJaPro2.4 on Stack Overflow
🌐
Mrhaki
blog.mrhaki.com › 2021 › 01 › java-joy-transform-stream-of-strings-to.html
Java Joy: Transform Stream Of Strings To List Of Key Value Pairs Or Map - Messages from mrhaki
January 27, 2021 - We can write a custom Collector that stores the first String value of a pair. When the next element in the Stream is processed by the Collector a Map object is created with the stored first value and the new value.
Top answer
1 of 9
11

here is the sample code for saving key-values with hashmap :

HashMap<String, String> data = new HashMap<String, String>();
data.put("key", "value");

or if the order matters to you use linkedHashMap :

HashMap<String, String> data = new LinkedHashMap<>();

the usage is the same;)

2 of 9
7

Data Structure Logic:

Hashmaps are used to access the content via its key.

In this sample, I guess you are scanning 'tuples' one by one and each tuple is different from other, so you won't need to access an old tuple via it's key.

So here, I suggest you to create the model class suitable for the key-value pairs and store them in a list. You can push that list when you are done.

Sample model for tuple:

public class KeyValuePair {
    private String key;
    private String value;
    public KeyValuePair(String key, String value) {
        this.key = key;
        this.value = value;
    }
}

Sample List to store:

List<KeyValuePair> keyValuePairList = new ArrayList<>();
keyValuePairList.add(new KeyValuePair("0", "816444014066"));
keyValuePairList.add(new KeyValuePair("1", "747083010945"));
keyValuePairList.add(new KeyValuePair("2", "816444010969"));

Storing:

If you cannot pass the data between activities, check out SQLite. You can store the data in SQLite and fetch it when needed. It is an offline database works on Android devices. You can delete the data when pushed to upstream.

Edit:

If the keys are the orders, you can simply use a String List like this:

List<String> keyValuePairList = new ArrayList<>();
keyValuePairList.add("816444014066");
keyValuePairList.add("747083010945");
keyValuePairList.add("816444010969");
Discussions

How to refactor this Java code so it creates a String List of key:value pairs as opposed to printing them out?
That code is a really horrible way to sort a list of hashmap entries. I don't know where you got that code, but the person who created it, is not an experienced developer. This is a simple way to sort them and add the key:value strings to an ArrayList: public static ArrayList sortAndMap(HashMap map) { var entryList = new ArrayList<>(map.entrySet()); Collections.sort(entryList, Comparator.comparing(Map.Entry::getValue)); var stringList = new ArrayList(); for(var e : entryList) { stringList.add(e.getKey() + ":" + e.getValue()); } return stringList; } You can also do it even better with Streams: public static List sortAndMap(HashMap map) { return map.entrySet().stream() .sorted(Comparator.comparing(Map.Entry::getValue)) .map((e) -> e.getKey() + ":" + e.getValue()) .collect(Collectors.toList()); } More on reddit.com
🌐 r/learnjava
5
2
March 7, 2021
java - Parsing a string with named sections and a key-value pair on each line - Code Review Stack Exchange
I have a response String as shown below which I need to parse it and store it my class. Format is shown below: task name followed by this dotted line ------------- which is also fixed and then just More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
May 1, 2016
regex - How to search a string of key/value pairs in Java - Stack Overflow
I have a String that's formatted like this: "key1=value1;key2=value2;key3=value3" for any number of key/value pairs. I need to check that a certain key exists (let's say it's called "specialkey"... More on stackoverflow.com
🌐 stackoverflow.com
Java convert List of key/value strings to Map - Stack Overflow
I have a List of strings which are actually keys and values: "key1", "value1", "key2", "value2", ... (every odd item is a key, every even — value). How can I convert it to Map like this "key1" -> " More on stackoverflow.com
🌐 stackoverflow.com
March 18, 2016
🌐
Baeldung
baeldung.com › home › java › core java › using pairs in java
Using Pairs in Java | Baeldung
March 13, 2024 - In this quick tutorial, we discuss the highly useful programming concept known as a Pair. Pairs provide a convenient way of handling simple key-to-value association and are particularly useful when we want to return two values from a method. A simple implementation of a Pair is available in the core Java libraries.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-convert-all-linkedhashmap-key-value-pairs-to-list-in-java
How to Convert all LinkedHashMap Key-Value pairs to List in Java? - GeeksforGeeks
July 23, 2025 - // Java program to Convert all LinkedHashMap // Key-Value pairs to List import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; public class Sias { public static void main(String[] args) { // create LinkedHashMap LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); // add elements in LinkedHashMap lhmap.put(1, "One"); lhmap.put(2, "Two"); lhmap.put(3, "Three"); lhmap.put(4, "Four"); lhmap.put(5, "Five"); // Create List 1 that store keys List<Integer> list1 = new ArrayList<Integer>(lhmap.keySet()); // display List 1 System.out.println("List 1 - " + list1); // Create List 2 that store values List<String> list2 = new ArrayList<String>(lhmap.values()); // display List 1 System.out.println("List 2 - " + list2); } } Output ·
🌐
Reddit
reddit.com › r/learnjava › how to refactor this java code so it creates a string list of key:value pairs as opposed to printing them out?
r/learnjava on Reddit: How to refactor this Java code so it creates a String List of key:value pairs as opposed to printing them out?
March 7, 2021 -

Hello

So I saw some code online that I implemented into my program to sort a hashmap<String, int> based on the values of the integers, and it works successfully but only outputs the values, I need to store the values into a String list but don't understand the code well enough to do this and have been failing repeatedly, it is confusing me to have so many brackets.

If anyone could point me in the right direction that'd be helpful, I don't even know what to google to find out how to do this, thanks.

method:

https://paste.ofcode.org/jTtkBHeMV8bEmzYdLLASrG

🌐
University of Toronto
individual.utoronto.ca › ssuepaul › API › applicationLogic › utility › KeyValuePair.html
applicationLogic.utility Class KeyValuePair
Key 'key1' is a string. keys = ... ...], ... ['valuen1', 'valuen2', ...] ] ... public KeyValuePair(java.lang.String[] keys, java.lang.String[] dataTypes, java.util.List<java.lang.String[]> data, byte[] binaryData)...
🌐
Baeldung
baeldung.com › home › java › java collections › java map › get values and keys as arraylist from a hashmap
Get Values and Keys as ArrayList From a HashMap | Baeldung
March 7, 2025 - List<String> keyList = new ArrayList<>(); List<String> valueList = new ArrayList<>(); for (Map.Entry<String, String> entry : DEV_MAP.entrySet()) { keyList.add(entry.getKey()); valueList.add(entry.getValue()); } assertKeyAndValueList(keyList, valueList); ...
Find elsewhere
🌐
Dev.java
dev.java › learn › using-maps-to-store-key-value-pairs
Using Maps to Store Key Value Pairs
Copyright © 2026 Oracle and/or its affiliates. All rights reserved. Terms of Use | Privacy | Trademarks
Top answer
1 of 2
4

Your current code is very good: it reads easily, it is properly indented and clean. I am sure one could come up with a complicated regular expression for parsing this String but using a StringReader like you have done is simple and effective. It is dynamic with regard to the number of elements to put in the map.

I only have a couple of comments:

  • You are trimming each line only to determine if they are blank with

    if (s.trim().isEmpty()) {
        continue;  // Skip empty line
    }
    

    If you expect lines to have spaces to trim then you could do it all the time.

  • Instead of having a setMetrics method that takes a map, I would have a addMetric method that adds a key/value pair into the map.

    public void addMetric(String key, String value) {
        metrics.put(key, value);
    }
    

    This way, you don't need to build the map yourself in the while loop.

  • To prevent from NullPointerException, it is a good idea to always initiaze maps and lists when they are in instance variables. You can do it inline like the following:

    public class NameMetrics {
    
        private String name;
        private Map<String, String> metrics = new HashMap<>();
    
    } 
    

    or in the default constructor.

  • The variable s in String s = reader.readLine(); could have a better name, like line.
  • The while(true) loop with an explicit break works correctly, but it might be easier to follow with the traditional pattern while ((line = reader.readLine()) != null) {.

With those couples changes, you can have:

BufferedReader reader = new BufferedReader(new StringReader(response));
NameMetrics current = null;
List<NameMetrics> result = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
    line = line.trim();
    if (line.isEmpty()) {
        continue; // Skip empty line
    }
    int cut = line.indexOf(':');
    if (cut == -1) {
        cut = line.indexOf('-');
        if (cut == -1) {
            continue;
        }
        current = new NameMetrics();
        current.setName(line.substring(0, cut));
        result.add(current);
    } else if (current != null) {
        current.addMetric(line.substring(0, cut), line.substring(cut + 1));
    }
}
2 of 2
5

First, I'd like to point out that if are you storing this from your program and reading it back from a file later, you'd be better off Serializing it. But since you're being given this file, let's move on.

Infinite Loops

It's generally discouraged to use while(true) loops. It's not particularly bad (in fact it's sometimes better), but it's always best to look for an alternative for readability sake. Instead, let's use while ((line = reader.readLine()) != null).

Initializing variables as null

I also see you initialized a few variables as null, but that isn't necessary since it's implied for classes. (Also note primitive variables are implied as 0 during initialization).

Using the output format to your advantage

You also have a cut variable that gets the index of the tokens, and then skips the line if it's blank. However, we know that the output is always going to be grouped into three lines, and we always know what those lines are going to be. We also know the data you really want is going to be the first three characters for the name, and everything after the first five characters for the tokens. Let's use that and make everything clear!

Putting it all together

String response = restTemplate.getForObject(url, String.class);
BufferedReader reader = new BufferedReader(new StringReader(response));
NameMetrics current;
Map<String, String> metricsHolder;
List<NameMetrics> result = new ArrayList<>();

String name, load, peak;

String nameline;
while ((nameline = reader.readLine()) != null) {
    name = nameLine.substring(0, 3);
    load = reader.readLine().substring(5);
    peak = reader.readLine().substring(5);
    reader.readline(); //eat empty line

    current = new NameMetrics();
    metricsHolder = new HashMap<>();    //No need to repeat the stuff inside the diamond operator
    metricsHolder.put("Load", load);
    metricsHolder.put("Peak", peak);

    current.setName(name);
    current.setMetrics(metricsHolder);
    result.add(current);
}

Handling varying keys and names

When there are a variable number of keys, we still know that they're all generally in the same format of the name followed dashes, then a list of key:value lines, then a blank line. We can still use this to our advantage as follows:

String name;
String[] mapValues;

final int KEY = 0, VALUE = 1;
String nameline, keyLine;
while ((nameline = reader.readLine().trim()) != null) {    //Loop until the end of the file
    name = nameLine.substring(0, nameLine.indexOf("-") + 1); //Plus because substring excludes last index

    metricsHolder = new HashMap<>();    //No need to repeat the stuff inside the diamond operator
    while (!(keyLine = reader.readLine().trim()).isEmpty()) {   //Loop until block ends with an empty line
        mapValues = reader.readLine().split(":");   //Split key:value format
        metricsHolder.put(mapValues[KEY], mapValues[VALUE]);
    }

    current = new NameMetrics();
    current.setName(name);
    current.setMetrics(metricsHolder);
    result.add(current);
}
🌐
Delft Stack
delftstack.com › home › howto › java › java key value pair
How to Implement Key Value Pair in Java | Delft Stack
February 12, 2024 - Initially, by importing the java.util package and specifically the Hashtable and Map classes. We declare and instantiate a Hashtable named keyValueTable, with explicit specifications that it will have String keys and Integer values. As we populate our Hashtable with key-value pairs, it’s important to note that Hashtable ensures the uniqueness of keys, and its synchronized nature makes it thread-safe.
🌐
JBoss
docs.jboss.org › jbossesb › docs › 4.0RC1 › javadoc › esb › org › jboss › soa › esb › helpers › KeyValuePair.html
KeyValuePair
Get the value associated with the specified key from the supplied list of Key Value Pairs. Returns the value from the first matching key. ... The value associated with the supplied key, or null if key not found. public static java.lang.String getValue(java.lang.String key, java.util.List<K...
🌐
CodeGym
codegym.cc › java blog › java objects › pairs in java
Pairs in Java
December 18, 2024 - Name: Alice Age: 25 In this example, we create a Pair instance named agePair containing a name (key) and an age (value). We then retrieve and print the name and age using the getKey() and getValue() methods.
🌐
Stack Overflow
stackoverflow.com › questions › 27298649 › setter-for-a-key-value-pair-list-object
java - Setter for a key value pair List object - Stack Overflow
December 5, 2014 - So in my program i then create ... List<String[]> results = getResults() for(String[] str : results) { KeyValuePair kvp = new KeyValuePair(str[0], str[1]); nvp.add(kvp) } } return new myList(nvp) }...
🌐
W3Schools
w3schools.com › java › java_hashmap.asp
Java HashMap
Now you can use methods like put() to add key/value pairs, get() to retrieve a value by key, and remove() to delete an entry - all by using keys instead of index numbers. ... // Import the HashMap class import java.util.HashMap; public class ...
🌐
Java Made Easy!
java-made-easy.com › java-collections.html
Java Collections - ArrayList and HashMap
If we look at the HashMap we just created, you will see <String, String&gt. This means that the first value (the key) is a String, and the second value is also a String.