【问题标题】:Java: the fastest way to filter List with 1m of objectsJava:用 1m 个对象过滤 List 的最快方法
【发布时间】:2021-08-28 08:25:25
【问题描述】:

现在我有了 ProductDTO 和产品列表。

这个列表可以包含 100 个对象,也可以包含 1m 个对象。

我正在从 csv 文件中读取此列表。

我现在如何过滤它:

productDtos.parralelStream()
    .filter(i -> i.getName.equals(product.getName))
    .filter(i -> Objects.equals(i.getCode(), product.getCode()))
    .map(Product::new)
    // getting object here

那么,解析它的最佳方法是什么?我想我应该使用多线程,一个线程将从列表的开头开始,另一个将从列表的末尾开始。

任何想法如何提高大数据案例中过滤列表的速度? 谢谢

【问题讨论】:

  • 如果您或那个可能拼写错误的“parralelStream”使用.parallel(),您还期望更多的并行性吗?

标签: java multithreading java-stream bigdata


【解决方案1】:

首先,我明白了,您已经将所有productsDtos 上传到内存中。 它可能会导致您的内存消耗非常高。 我建议您按行读取 CSV 文件并逐个过滤它们。在这种情况下,您的代码可能如下所示:

public class Csv {
    public static void main(String[] args) {
        File file = new File("your.csv");
        try (final BufferedReader br = new BufferedReader(new FileReader(file))) {
            final List<String> filtered = br.lines().parallel()
                    .map(Csv::toYourDTO)
                    .filter(Csv::yourFilter)
                    .collect(Collectors.toList());
            System.out.println(filtered);
        } catch (IOException e) {
            //todo something with the error
        }
    }

    private static boolean yourFilter(String s) {
        return true; //todo
    }

    private static String toYourDTO(String s) {
        return "";//todo
    }
}

【讨论】:

  • 斯帕西博布拉蒂什卡!
【解决方案2】:

我曾经构造map并使用get来避免循环过滤。

例如,如果您有 1 个产品的 N 代码,您可以这样做:

Map<String, Map<String, List<ProductDTO>>> productDtoByNameAndCode= productDtos.stream().collect(groupingBy(ProductDTO::getName, groupingBy(ProductDTO::getCode)));

那么你只需要为每个产品做:

List<ProductDTO> correspondingProductDTOs = productDtoByNameAndCode.get(product.getName()).get(Product.getCode());

这样,您不必每次都为每个产品过滤所有列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-20
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多