英文:
How to set list of chars and list of integers into one list?
问题
private List
List<Object> combinedList = new ArrayList<>();
for (Character key : mapKeyToList) {
combinedList.add(key + " - " + values.iterator().next());
values.remove(values.iterator().next());
}
return combinedList;
}
英文:
How to set list of chars and list of integers into one list? I have two lists which I took from hash map and now I have to format it into pretty view. After formatting I have two lists one of integers and other one of characters. Is it possible to put this values into one array list
private List<Character> convertToList(){
Set<Character> mapKeyToList = output().keySet();
List<Character> keys = new ArrayList<>(mapKeyToList);
return keys;
}
private List<Integer> convertInts(){
Collection<Integer> values = output().values();
List<Integer> quantity = new ArrayList<>(values);
return quantity;
}
Example of output :
"char" - int
"char" - int
"char" - int
答案1
得分: 3
你可以从你的映射中获取 entrySet
并获得一个新的 ArrayList。
List<Map.Entry<Character, Integer>> res = new ArrayList<>(output().entrySet());
你可以使用 .getKey()
和 .getValue()
来获取键和值。
for (Map.Entry<Character, Integer> entry : res) {
Character c = entry.getKey();
Integer i = entry.getValue();
// 格式化
}
在这里,你也可以直接在循环中使用 `resultMap.entrySet()` 而不是 `res`。
<details>
<summary>英文:</summary>
You can get the `entrySet` from your map and get in new ArrayList
List<Entry<Character, Integer>> res = new ArrayList<>(output().entrySet());
You can get key and value using `.getKey()` and `.getValue()`
for (Entry<Character, Integer> entry : res) {
Character c = entry.getKey();
Integer i = entry.getValue();
// formatting
}
Here you can directly use `resultMap.entrySet()` instead of `res` in loop also.
</details>
# 答案2
**得分**: 0
假设这两个列表的大小相同(如果它们是从同一个映射创建的话),您可以使用 for 循环从每个列表中提取元素并填充新列表。
```java
List<String> newList = new ArrayList<>();
for (int i = 0; i < ints.size(); i++) {
newList.add(String.format("%s - %d", chars.get(i), ints.get(i)));
}
当然,如果您使用的是 Java 8 或更高版本,您还可以使用 Streams API 遍历映射并执行此操作。
List<String> result = values.entrySet().stream()
.map(x -> String.format("%s - %d", x.getKey(), x.getValue()))
.collect(Collectors.toList());
英文:
Assuming that both lists are the same size (which they should be, if they are created from the same map), you can just use a for loop to pull elements from each list and populate the new list.
List<String> newList = new ArrayList<>();
for (int i = 0; i < ints.size(); i++) {
newList.add(String.format("%s - %d", chars.get(i), ints.get(i)));
}
Of course, you could also loop over the map and do this with the Streams API if you are using Java 8 or later.
List<String> result = values.entrySet().stream()
.map(x -> String.format("%s - %d", x.getKey(), x.getValue()))
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论