如何从对象列表中将所有字符串添加到ArrayList最有效?

时间:2023-01-28 22:58:59

NB: Please edit the title if you could write it better.. I've no idea how to explain it better..

注意:如果你能写得更好,请编辑标题..我不知道如何更好地解释它...

Over to the problem: I'm using autocomplete in a javafx form and need to get all the customers firstName into a list for Strings. I've used JPA to get all of the customers from the database. So i'm a bit worried about the speed of my code.. You see why..

解决问题:我正在以javafx形式使用自动完成,需要将所有客户firstName放入字符串列表中。我使用JPA从数据库中获取所有客户。所以我有点担心代码的速度..你明白为什么..

Code example:

public static List<String> getAllFirstNamesCustomer() {
        List<String> names = new ArrayList<>();
        for (Customer c : CustomerBean.getAllCustomers()) {
            names.add(c.getCName());
        }
        List<String> output =
            new ArrayList<>(new LinkedHashSet<>(names));
        return output;

    }  

EDIT:

Think i found a better way:

我想我找到了一个更好的方法:

public static List<String> getAllFirstNamesCustomer() {
    return em.createNativeQuery("select DISTINCT cname from customer").getResultList();  
}

1 个解决方案

#1


1  

Good option would be for the database driver to stream the data. A workaround and with a larger customer data set, you can leverage Java 8'sparallel streams which takes advantage of all cores of the CPU, with one liner

好的选择是数据库驱动程序流式传输数据。解决方法和更大的客户数据集,您可以利用Java 8的并行流,利用CPU的所有核心,一个内核

List<String> names = CustomerBean.getAllCustomers().parallelStream().map(c.getCName()).collect(toList());

#1


1  

Good option would be for the database driver to stream the data. A workaround and with a larger customer data set, you can leverage Java 8'sparallel streams which takes advantage of all cores of the CPU, with one liner

好的选择是数据库驱动程序流式传输数据。解决方法和更大的客户数据集,您可以利用Java 8的并行流,利用CPU的所有核心,一个内核

List<String> names = CustomerBean.getAllCustomers().parallelStream().map(c.getCName()).collect(toList());