java - 将数组转换为列表,然后转换为映射
问题描述
我想如果有人可以查看这段代码,代码应该将数组转换为列表,然后转换为地图。键应具有列表元素的值,如果是偶数,则该值应为 True,如果为奇数,则该值应为 False。数组是“8, 6, 1, 5, 3, 9, 2”。我很确定这是正确的方法,但是在打印地图时,我得到了很多线条,这是我第一次使用地图,所以我不确定这是否应该是这样,或者我搞砸了。代码:
static public void toMap(int x[]) {
List<Integer> list = new ArrayList<>();
Map<Integer, String> map = new HashMap<>();
for (int t : x) {
list.add(t);
}
for(int z : list) {
String tf;
if(z % 2 == 0)
tf = "True";
else
tf = "False";
map.put(z,tf);
for (Map.Entry<Integer, String> mp : map.entrySet()) {
System.out.println(mp.getKey() + "/" + mp.getValue());
}
}
}
打印时得到这个:
任何帮助/提示将不胜感激,在此先感谢!
解决方案
您正在 for 循环内打印,这导致了问题。您需要将其移到 for 循环之外。这是更新的代码 -
static public void toMap(int[] x) {
List<Integer> list = new ArrayList<>();
for (int t : x) {
list.add(t);
}
Map<Integer, String> map = new HashMap<>();
for(int z : list) {
String tf;
if(z % 2 == 0)
tf = "True";
else
tf = "False";
map.put(z,tf);
}
for (Map.Entry<Integer, String> mp : map.entrySet()) {
System.out.println(mp.getKey() + "/" + mp.getValue());
}
}
您也可以将其简化如下 -
public static void main(String[] args) {
Integer[] array = {8, 6, 1, 5, 3, 9, 2};
toMap(array);
}
static public void toMap(Integer[] x) {
List<Integer> list = Arrays.asList(x);
Map<Integer, String> map = new HashMap<>();
list.forEach(i -> {
if (i % 2 == 0)
map.put(i, "True");
else
map.put(i, "False");
});
System.out.println(map);
}
推荐阅读
- python - 如何在 Windows 机器上加载 Spacy 对象(在 Ubuntu 中腌制)?
- swift - 具有缩放和 alpha 的 UIView 动画
- c# - 如何设置一个在 C# 中使用字符串?
- java - 如何使用我自己的属性、规范和可分页创建自定义 Spring Data JPA 查找方法?
- sql-server - SQL Server 全文搜索在时间窗口内的最大性能限制
- c# - AspNet 用户声明丢失
- google-apps-script - getActiveCell() 总是返回 1,1
- ansible - Ansible 测试变量以什么开头
- android - 在 Android 中将字符串作为文件附件共享
- swift - 如何告诉用户准确的度数是朝北还是朝东?