需要快速查找时,使用Map,通过key直接访问
仅需要存储数据,使用List
public class ListVsMapApplication {
public static void main(String[] args) throws InterruptedException {
int elementCount = 1000000;
int loopCount = 1000;
StopWatch stopWatch = new StopWatch();
stopWatch.start("listSearch");
Object list = listSearch(elementCount, loopCount);
System.out.println(ObjectSizeCalculator.getObjectSize(list));
stopWatch.stop();
stopWatch.start("mapSearch");
Object map = mapSearch(elementCount, loopCount);
stopWatch.stop();
System.out.println(ObjectSizeCalculator.getObjectSize(map));
System.out.println(stopWatch.prettyPrint());
TimeUnit.HOURS.sleep(1);
}
private static Object listSearch(int elementCount, int loopCount) {
//首先使用IntStream生成1到elementCount的顺序流
//使用mapToObj将其映射成Order对象的Stream。
//并使用collect收集到一个List中。
List<Order> list = IntStream.rangeClosed(1, elementCount).mapToObj(i -> new Order(i)).collect(Collectors.toList());
//然后进行loopCount次搜索:
IntStream.rangeClosed(1, loopCount).forEach(i -> {
//每次随机生成一个id。
int search = ThreadLocalRandom.current().nextInt(elementCount);
//在List中使用stream()过滤查找匹配的Order。findFirst()返回第一个匹配元素。orElse(null)用于处理未找到的情况。
Order result = list.stream().filter(order -> order.getOrderId() == search).findFirst().orElse(null);
//最后使用Assert判断确保找到了匹配的Order。
Assert.assertTrue(result != null && result.getOrderId() == search);
});
//返回生成的List。
return list;
}
private static Object mapSearch(int elementCount, int loopCount) {
Map<Integer, Order> map = IntStream.rangeClosed(1, elementCount).boxed().collect(Collectors.toMap(Function.identity(), i -> new Order(i)));
IntStream.rangeClosed(1, loopCount).forEach(i -> {
int search = ThreadLocalRandom.current().nextInt(elementCount);
Order result = map.get(search);
Assert.assertTrue(result != null && result.getOrderId() == search);
});
return map;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
static class Order {
private int orderId;
}
}
学习:Java 业务开发常见错误 100 例学习笔记