public class test {
public static void main(String[] args) throws InterruptedException {
List<Member> list1 = new ArrayList<>();
List<Member> list2 = new ArrayList<>();
for (int i = 0; i < 30000; i++) {
Date date = new Date();
//每个元素有名字
list1.add(new Member((i + 1), "技术客", (i + 1), date));
if (i % 2 == 0) {
//对2取模无名字
list2.add(new Member((i + 1), null, (i + 1), date));
}
}
//双for循环嵌套测试
long s1 = System.currentTimeMillis();
int forNumber = 0;
for (Member m2 : list2) {
if (m2.getName() == null) {
for (Member m1 : list1) {
if (m1.getId().intValue() == m2.getId().intValue()) {
// System.out.println(m2.getId()+" Name 值为空!!!");
forNumber++;
}
}
}
}
long s2 = System.currentTimeMillis();
System.out.println("双for循环查询时间为:" + (s2 - s1) + "(毫秒),一共查询出" + forNumber + "条数据 \n\n\n");
//TimeUnit.SECONDS.sleep(3);
//map查询测试
long s3 = System.currentTimeMillis();
int mapNumber = 0;
Map<Integer, Member> map = new HashMap<>();
for (Member m1 : list1) {
map.put(m1.getId(), m1);
}
for (Member m2 : list2) {
if (m2.getName() == null) {
Member m = map.get(m2.getId());
if (m != null) {
mapNumber++;
}
}
}
long s4 = System.currentTimeMillis();
System.out.println("使用map结构查询时间为:" + (s4 - s3) + "(毫秒),一共查询出" + mapNumber + "条数据 \n\n\n");
//stream流方法1
for (Person e1 : list1) {
list2.stream().anyMatch(e2 -> {
if (e1.getId() == e2.getId()) {
e1.setName(e2.getName());
}
return false;
});
}
//stream流方法1
list1.stream().forEach(e1 -> list2.stream().anyMatch(e2 -> {
if (e1.getId() == e2.getId()) {
e1.setName(e2.getName());
}
return false;
}));
System.out.println(list1);
}
}
双重for循环优化
最新推荐文章于 2024-04-14 16:25:32 发布