面试题答案
一键面试import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Product {
private double price;
private String category;
private int rating;
public Product(double price, String category, int rating) {
this.price = price;
this.category = category;
this.rating = rating;
}
public double getPrice() {
return price;
}
public String getCategory() {
return category;
}
public int getRating() {
return rating;
}
}
public class Main {
public static void main(String[] args) {
List<Product> productList = new ArrayList<>();
productList.add(new Product(200, "electronics", 4));
productList.add(new Product(300, "clothes", 3));
productList.add(new Product(400, "electronics", 5));
List<Product> filteredList = productList.stream()
.filter(product -> product.getPrice() >= 100 && product.getPrice() <= 500
&& "electronics".equals(product.getCategory())
&& product.getRating() >= 4)
.collect(Collectors.toList());
System.out.println(filteredList);
}
}
大数据量下的性能优化分析
- 并行流:
- 使用并行流
parallelStream()
代替stream()
。并行流会将数据分成多个部分,在多个线程上同时处理,利用多核CPU的优势。例如:
- 使用并行流
List<Product> filteredList = productList.parallelStream()
.filter(product -> product.getPrice() >= 100 && product.getPrice() <= 500
&& "electronics".equals(product.getCategory())
&& product.getRating() >= 4)
.collect(Collectors.toList());
- 但并行流也有开销,对于数据量较小或计算任务简单的情况,并行流可能反而会降低性能。因为并行化带来的线程创建、数据分割和合并等操作会消耗额外资源。
2. 减少不必要计算:
- 如果category
属性在数据量较大时是相对固定的,且electronics
类别占比较小,可以先根据category
过滤,再进行其他条件过滤。这样可以减少后续条件过滤的数据量。例如:
List<Product> filteredList = productList.stream()
.filter(product -> "electronics".equals(product.getCategory()))
.filter(product -> product.getPrice() >= 100 && product.getPrice() <= 500
&& product.getRating() >= 4)
.collect(Collectors.toList());
- 数据结构优化:
- 如果数据是持续动态变化的,考虑使用更适合过滤操作的数据结构,比如
TreeSet
或HashSet
。HashSet
在查找操作上有较好的性能,若对商品进行唯一性标识并使用HashSet
存储,在过滤时可以更快地定位和筛选。但需要注意,HashSet
不保证元素顺序。 - 如果数据量非常大,超出内存限制,可以考虑使用分布式计算框架,如Apache Spark。Spark可以在集群环境下处理大规模数据,通过分布式存储和计算来优化性能。
- 如果数据是持续动态变化的,考虑使用更适合过滤操作的数据结构,比如