2023.1.3日学习内容(map统计升级版)

1,map集合如何统计

public static void main(String[] args) {
    Map<Character, Integer> map = new HashMap<>();
    Scanner scanner = new Scanner(System.in);
    String word = scanner.next();
    char[] chars = word.toCharArray();
    for (char aChar : chars) {
        Integer count = map.get(aChar);
        map.put(aChar, count == null ? 1 : count + 1);
    }
    map.forEach((s, integer) -> System.out.println(s+"   "+integer));
}

统计输入的字母a有几个b有几个等等

asxsa
a   2
s   2
x   1

2,将map统计加入到统计文件夹中文件后缀的个数

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("请输入您查找的地址");
    String address = scanner.next();
    Map<String, Integer> map = new HashMap<>();
    File file = new File(address);
    find(map, file);
    System.out.println(map);
}

private static void find(Map<String, Integer> map, File file) {
    File[] child = file.listFiles();
    for (File f : child) {
        if (f.isFile()) {
            String endName = f.getName().split("\\.")[1];
            Integer count = map.get(endName);
            map.put(endName, count == null ? 1 : count + 1);
        } else {
            find(map, f);
        }
    }
}

得出的结果为

C:\Users\19191\Desktop\test
{xlsx=1, txt=1, bmp=2, html=2, docx=1}

这里使用了递归,查找输入的地址下面文件是否为文件夹,如果是文件,就添加到map里计数,如果是文件夹,就进入该地址再次遍历

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值