两个list循环统计次数

这个博客展示了一个Java程序,用于在一百万个Person对象的列表中,统计每个对象的name属性中包含特定关键词的次数。程序使用了StringBuilder构建字符串,List填充Person对象,并通过遍历和计数方法实现查找。关键词存储在另一个List中,最后结果存储在HashMap中。程序还涉及到字符串操作、多线程和性能测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:在一个list中,找到每个对象里面包含另一个lis关键词的次数。

 public static void main(String[] args) {
        String res = "你的我的春天啊的大撒发生我爱大方,撒饭撒的方式阿多少钱dsfd324大方三分大赛的我的的好嘎嘎";
        StringBuilder a = new StringBuilder();
        long timeMillis1 = System.currentTimeMillis();
        System.out.println(timeMillis1);
        List<Person> list = Lists.newArrayList();
        for (int i = 0; i < 1000000; i++) {
            Person person = new Person();
            person.setId(i);
            person.setName(res);
            list.add(person);
        }
        long timeMillis2 = System.currentTimeMillis();
        System.out.println(timeMillis2 - timeMillis1);
        System.out.println(list.size());

        String b = "我的你";
        String c = "我的";
        String d = "asfasfasf";
        String y = "的";
        List<String> objects = new ArrayList<>();
        objects.add(b);
        objects.add(c);
        objects.add(d);
        objects.add(y);
        Map<String, Integer> result = new HashMap<>(objects.size());
        objects.add(b);
        objects.add(c);
//parallelStream 多线程(list.parallelStream().forEach)用不用效果差不多
        list.forEach(e -> objects.forEach(n -> {
            int count = count(e.getName(), n);
            if (count == 0) {
                return;
            }
            if (result.computeIfPresent(n, (k, v) -> v + count) == null) {
                result.put(n, count);
            }
        }));
        Map<String, Object> er = new HashMap<>();
        er.put("sdf", result);
        System.out.println(JsonMapperUtils.toJson(result));
        System.out.println(JsonMapperUtils.toJson(er));
        System.out.println(System.currentTimeMillis() - timeMillis2);
    }

    public static int count(String name, String n) {
        int count = 0;
        while (name.contains(n)) {
            name = name.substring(name.indexOf(n) + 1);
            ++count;
        }
        return count;
    }

    @Data
    static class Person {
        private String name;
        private int id;
        private int count;
    }

    @Data
    static class Total {
        private String name;
        private int count;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值