英文:
Is there a Java way to format an array output by removing the curly brackets around each key-value pair?
问题
我的代码可以通过从SQL查询返回预期的键值对输出来正常工作,但输出的格式需要更改。我尝试删除数组中包含的每个键值对周围的大括号,但我没有成功。
这是我尝试过的,但没有成功:
public List<Map<String, String>> getDemoNames() {
List<Map<String, String>> demoNames = new ArrayList<>();
for (Object result : resultList) {
Object[] row = (Object[]) result;
Map<String, String> map = new HashMap<>();
String key = String.valueOf(row[0]).trim().replaceAll("[{}]", ""); //我尝试以这种方式删除大括号
String value = String.valueOf(row[1]).trim().replaceAll("[{}]", "");
map.put(key, value);
demoNames.add(map);
System.out.println(demoNames);
}
return demoNames;
}
输出:[{001=DEMO}, {002=APPLE}, {003=GOOGLE}, {004=ALAMANCE COUNTY}]
我想要的输出格式是:
[{001=DEMO, 002=APPLE, 003=GOOGLE, 004=ALAMANCE COUNTY}]
如何实现这个目标?
英文:
My code works OK by returning the expected key-value pair output from an sql query, however the formatting of the output needs to be changed. I tried removing the curly brackets around each key-value pair contained in the array, but I couldnt succeed with that.
This is what I have tried, but it didn't work:
public List<Map<String, String>> getDemoNames() {
List<Map<String, String>> demoNames = new ArrayList<>();
for (Object result : resultList) {
Object[] row = (Object[]) result;
Map<String, String> map = new HashMap<>();
String key = String.valueOf(row[0]).trim().replaceAll("[{}]", ""); //I tried removing the curly bracket this way
String value = String.valueOf(row[1]).trim().replaceAll("[{}]", "");
map.put(key, value);
demoNames.add(map);
System.out.println(demoNames);
}
return demoNames;
}
Output: [{001=DEMO}, {002=APPLE}, {003=GOOGLE}, {004=ALAMANCE COUNTY}]
What I want is to get the output in this format:
[{001=DEMO, 002=APPLE, 003=GOOGLE, 004=ALAMANCE COUNTY}]
How do I achieve this?
答案1
得分: 2
- 在第一次创建地图之后,将每个地图的单个条目添加到列表中(因为地图是在循环内创建然后添加到列表中)。
有至少三种选项可以按照您请求的格式获取输出:
-
首先以期望的布局填充您的数据结构。也就是说,您有一个包含单个地图的列表(地图包含所有条目)。 可以假设这实际上是您想要的解决方案: 在循环外创建地图,然后在循环内填充它(每次循环迭代都会将一个条目放入地图中)。
-
手动构建输出字符串:
boolean first = true; final StringBuilder sb = new StringBuilder(); sb.append("[{"); for (final Map<String, String> map : demoNames) { for (final Map.Entry<String, String> entry : map.entrySet()) { if (!first) sb.append(", "); first = false; sb.append(entry.getKey()).append('=').append(entry.getValue()); } } sb.append("}]"); System.out.println(sb);
-
将地图转换为所期望的格式,然后在地图上使用
toString
:final Map<String, String> map = new HashMap<>(); for (final Map<String, String> demoName : demoNames) { map.putAll(demoName); } System.out.println(map);
英文:
You have a list of maps with each map only having a single entry (because the map is created inside the loop and then added to the list).
There are at least three options to get the output in the format you request:
-
Populate your data structure in the expected layout in the first place. Meaning that you have a list with a single map (and the map contains all the entries). Presumably, this is the solution which you actually want: Create the map outside the loop, then populate it from within the loop (each loop iteration puts an entry into the map).
-
Manually build the output string:
boolean first = true; final StringBuilder sb = new StringBuilder(); sb.append("[{"); for (final Map<String, String> map : demoNames) { for (final Map.Entry<String, String> entry : map.entrySet()) { if (!first) sb.append(", "); first = false; sb.append(entry.getKey()).append('=').append(entry.getValue()); } } sb.append("}]"); System.out.println(sb);
-
Transform the map into the expected format, then use
toString
on the map:final Map<String, String> map = new HashMap<>(); for (final Map<String, String> demoName : demoNames) { map.putAll(demoName); } System.out.println(map);
答案2
得分: 1
我认为您想要返回一个Map
,而不是一组Map
:
public Map<String, String> getDemoNames() {
Map<String, String> map = new LinkedHashMap<>();
for (Object result : resultList) {
Object[] row = (Object[]) result;
String key = String.valueOf(row[0]);
String value = String.valueOf(row[1]);
map.put(key, value);
}
// 考虑从调用点打印,以保持代码的整洁
System.out.println(map);
return map;
}
使用LinkedHashMap
而不是HashMap
,可以按插入顺序迭代其条目,因此调用其toString()
会按照resultList
的顺序渲染。
考虑将具有适当命名的字符串字段的类的对象存储在resultList
中,而不是Object[]
,这将使您的代码更加健壮和可读。
英文:
I think you want a Map returned, not a List of Maps:
public Map<String, String> getDemoNames() {
Map<String, String> map = new LinkedHashMap<>();
for (Object result : resultList) {
Object[] row = (Object[]) result;
String key = String.valueOf(row[0]);
String value = String.valueOf(row[1]);
map.put(key, value);
}
// Consider printing from the call point instead to keep this code clean
System.out.println(map);
return map;
}
Using a LinkedHashMap
instead of a HashMap
iterates over its entries in insertion order, so calling its toString()
will render in the same order as resultList
.
Consider storing objects of a class with appropirately named String fields in resultList
instead of Object[]
, which would make your code less brittle and more readable.
答案3
得分: 1
这似乎是一个 XY 问题。看起来你真正的问题是生成特定外观的输出,而你选择了错误的中间数据结构。现在你正试图通过对数据结构的 toString()
输出进行巧妙的转换来弥补错误的选择,以获得你想要的输出。
如果你不知道映射的键/值对中包含什么内容,那么使用 replaceAll
来删除不需要的括号是不稳定的。
但我认为问题更深层次。你正在创建一个包含一个元素的映射列表,但你试图使其看起来像包含一个单一(组合的)映射的列表。那么...为什么不将其创建为一个单一的映射呢?
public List<Map<String, String>> getDemoNames() {
List<Map<String, String>> demoNames = new ArrayList<>();
Map<String, String> map = new LinkedHashMap<>();
for (Object result : resultList) {
Object[] row = (Object[]) result;
// 以下代码从键和值字符串中移除花括号。这是不必要的...除非你希望在结果列表中出现这种内容。
String key = String.valueOf(row[0]).trim().replaceAll("[{}]", "");
String value = String.valueOf(row[1]).trim().replaceAll("[{}]", "");
map.put(key, value);
}
demoNames.add(map);
System.out.println(demoNames);
return demoNames;
}
此外,在这里没有明显的理由要有这个列表。它似乎没有任何目的。(除非可能要保留键值对的顺序。而 LinkedHashMap
会保留顺序。)
另一方面...如果你真的需要生成映射列表,那么按照你的要求格式化数据的最佳方式是使用 for
循环或流迭代映射。请参考 @knittl 的答案示例。
英文:
This seems like an XY problem. It seems like your real problem is generating output that looks a certain way, and you have picked the wrong intermediate data structure. Now you are trying to compensate for the wrong choice with some clever transformation of the toString()
output from the data structure to get your desired output.
If you have no knowledge of what is in the map's key / value pairs, then using replaceAll
to remove unwanted brackets is fragile.
But I think the problem is deeper than that. You are creating a list of maps where each map contains one element, but you are trying to make it look like a list containing a single (combined) map. So ... why not create it as a single map?
public List<Map<String, String>> getDemoNames() {
List<Map<String, String>> demoNames = new ArrayList<>();
Map<String, String> map = new LinkedHashMap<>();
for (Object result : resultList) {
Object[] row = (Object[]) result;
// The following removes braces from the key and
// value strings. This is unnecessary ... unless
// you are expecting such stuff in the result list.
String key = String.valueOf(row[0]).trim().replaceAll("[{}]", "");
String value = String.valueOf(row[1]).trim().replaceAll("[{}]", "");
map.put(key, value);
}
demoNames.add(map);
System.out.println(demoNames);
return demoNames;
}
Furthermore, there isn't any obvious reason to have the list here. It doesn't appear to serve any purpose. (Except maybe to preserve the order of the key-value pairs. And the LinkedHashMap
preserves that.)
On the other hand ... if you really do need to generate a list of maps, then the best way to format that data as you want would be iterate the maps using for
loops or streams. See @knittl's answer for example.
答案4
得分: 0
你也可以尝试这种方式:
String output = getDemoNames().stream().
flatMap(m -> m.entrySet().stream()).
map(e -> e.getKey() + "=" + e.getValue()).
collect(Collectors.joining(", ", "[{", "}]"));
System.out.println(output);
英文:
You could possibly try it this way too:
String output = getDemoNames().stream().
flatMap(m ->m.entrySet().stream()).
map(e ->e.getKey() + "=" + e.getValue()).
collect(Collectors.joining(", ", "[{", "}]"));
System.out.println(output);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论