Here's how you can convert the linked hashmap into a single string separated by underscores using Java:
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// Create the LinkedHashMap and populate it with the given values
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("triggerIdx", "IDX");
map.put("keywords", "스톤헨지");
map.put("category", "돌");
// Check if the map is empty and handle accordingly
if (map.isEmpty()) {
System.out.println("The map is empty.");
return;
}
// Initialize a StringBuilder to construct the result string
StringBuilder result = new StringBuilder();
// Iterate through the map and append key-value pairs to the result
for (Map.Entry<String, String> entry : map.entrySet()) {
if (result.length() > 0) {
result.append("_");
}
result.append(entry.getKey()).append("_").append(entry.getValue());
}
// Convert StringBuilder to String and print the result
String finalString = result.toString();
System.out.println(finalString);
}
}
Explanation
Create and Populate LinkedHashMap:
- A
LinkedHashMap
is created and populated with the given key-value pairs to maintain the insertion order.
- A
StringBuilder Initialization:
- A
StringBuilder
is used to efficiently build the result string.
- A
Iterate Through the Map:
- The code iterates through the entries of the map. For each entry, it appends the key and value to the
StringBuilder
, separated by an underscore. If theStringBuilder
already contains some text, an additional underscore is added before appending the new key-value pair.
- The code iterates through the entries of the map. For each entry, it appends the key and value to the
Convert to String and Print:
- The
StringBuilder
content is converted to aString
, which is then printed.
- The
When you run this Java code, it will output:
triggerIdx_IDX_keywords_스톤헨지_category_돌
728x90
'200===Dev Language > Java' 카테고리의 다른 글
자바 8과 자바 18의 주요 차이점 (0) | 2024.06.27 |
---|---|
JVM Garbage Collection (0) | 2024.06.08 |
JVM Introduced (0) | 2024.06.08 |
Java CheatSheet (0) | 2024.05.25 |
Java Native Memory Tracking(JCMD) 메모리 모니터링 툴 (0) | 2024.05.25 |