需求:在一个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;
}