如何将LinkedHashMap中字符串格式数值转换为double类型?
Hey there! As a fellow Java learner, I get exactly what you're trying to do—turn those string-based numeric values into actual double types so you can run calculations like averages. Let's go through a few straightforward solutions that fit your scenario:
1. Modify Your Existing Code to Store Doubles Directly
The simplest fix is to adjust your LinkedHashMap's generic type to hold List<Double> instead of List<String>, then convert the string values to double as you process them. This avoids needing a post-conversion step entirely.
Here's the updated version of your code:
List<String> stringList = Arrays.asList(tm.split(" |,")); Map<String, List<Double>> mapString = new LinkedHashMap<>(); stringList.forEach(s1 -> { String[] splitedStrings = s1.split(": "); String key = splitedStrings[0].replaceAll("[^A-Za-z0-9]",""); // Convert the string value directly to Double Double value = Double.parseDouble(splitedStrings[1].trim()); // Simplify null check with computeIfAbsent mapString.computeIfAbsent(key, k -> new ArrayList<>()).add(value); });
Note: I used computeIfAbsent to clean up the null check logic—it's a more concise way to initialize a list for new keys.
2. Convert an Existing String-Based Map to Double-Based
If you already have a Map<String, List<String>> that needs converting, you can create a helper method using Java Streams to transform it:
private static Map<String, List<Double>> convertToDoubleMap(Map<String, List<String>> stringMap) { Map<String, List<Double>> doubleMap = new LinkedHashMap<>(); for (Map.Entry<String, List<String>> entry : stringMap.entrySet()) { List<Double> doubleValues = entry.getValue().stream() .map(Double::parseDouble) .collect(Collectors.toList()); doubleMap.put(entry.getKey(), doubleValues); } return doubleMap; }
This approach is clean and leverages modern Java features to handle the conversion in one pass.
3. (Recommended) Use Gson to Parse JSON Directly into Typed Objects
Since you're already using Gson, the most maintainable long-term approach is to parse the JSON into strongly typed Java classes instead of manually splitting strings. This eliminates parsing errors and makes your code much easier to read and extend.
First, define classes that match your JSON structure:
class TonalData { private double frequency; private double level; private double bw; private double snr; private double median; // Add getters for each field (required to access the values later) public double getFrequency() { return frequency; } public double getLevel() { return level; } public double getBw() { return bw; } public double getSnr() { return snr; } public double getMedian() { return median; } } class TonalMessage { private String groupId; private double timestamp; private List<TonalData> tones; // Getters public String getGroupId() { return groupId; } public List<TonalData> getTones() { return tones; } }
Then parse the JSON with Gson:
String rawJson = "{\"groupId\":\"id3_x_\",\"timestamp\":1.591712740507E9,...}"; // Your full JSON string Gson gson = new Gson(); TonalMessage message = gson.fromJson(rawJson, TonalMessage.class);
Now you can easily perform calculations like averaging frequencies:
// Calculate average frequency double totalFrequency = 0.0; List<TonalData> tones = message.getTones(); for (TonalData tonal : tones) { totalFrequency += tonal.getFrequency(); } double avgFrequency = totalFrequency / tones.size();
This method is far less error-prone than manual string splitting and aligns with standard Java development practices.
Feel free to ask if you need clarification on any of these steps—learning Java takes time, and it's totally okay to break things down piece by piece!
内容的提问来源于stack exchange,提问作者Dinomking 3

