System.out::println可以用于Map集合吗
时间: 2023-07-30 11:07:11 浏览: 51
不可以直接使用System.out::println打印Map集合,因为Map集合不是一个可以直接输出的数据类型。需要使用Map的方法,比如entrySet()方法,将Map转换为可迭代的集合,然后遍历输出。例如:
```
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 2);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
```
这样就可以输出Map集合中的键值对了。
相关问题
import java.util.Map; public class test { public static void main(String[] args) { String a = "i am zjr form china am"; System.out.println(treemap.wordCount(a)); System.out.println(hashmap2.wordCount(a)); Map<String, Integer> stringIntegerMap = treemap.wordCount(a); Map<String, Integer> stringIntegerMap1 = hashmap2.wordCount(a); System.out.println(stringIntegerMap1.keySet()); System.out.println(stringIntegerMap1.values()); } } 这段代码的作用是什么
这段代码的作用是测试一个名为`wordCount`的方法在`treemap`和`hashmap2`中的运行结果。首先,将字符串`"i am zjr form china am"`赋给变量`a`。然后,分别使用`treemap`和`hashmap2`中的`wordCount`方法对字符串进行单词计数,并将结果打印出来。接着,将计数结果分别赋给`stringIntegerMap`和`stringIntegerMap1`。最后,打印出`stringIntegerMap1`的键集合和值集合。整个代码的目的是测试并展示不同的实现方式(使用TreeMap和HashMap)对字符串进行单词计数所得到的结果。
在控制台输入一系列整数,用空格隔开,使用Map集合统计各个整数的出现次数 public class MapDemo2 { public static void main(String[] args) { System.out.println("请输入一系列整数,用空格隔开:"); }}
```
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class MapDemo2 {
public static void main(String[] args) {
System.out.println("请输入一系列整数,用空格隔开:");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] nums = input.split(" ");
Map<Integer, Integer> map = new HashMap<>();
for (String num : nums) {
int n = Integer.parseInt(num);
if (map.containsKey(n)) {
map.put(n, map.get(n) + 1);
} else {
map.put(n, 1);
}
}
System.out.println("各个整数的出现次数为:");
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "出现了" + entry.getValue() + "次");
}
}
}
```
运行示例:
```
请输入一系列整数,用空格隔开:
1 2 3 4 5 1 2 3 1 2
各个整数的出现次数为:
1出现了3次
2出现了3次
3出现了2次
4出现了1次
5出现了1次
```