【问题标题】:Is there any differences between this two ways of looping and which one is preferable to be used?这两种循环方式之间有什么区别吗?最好使用哪一种?
【发布时间】:2017-04-02 15:58:41
【问题描述】:

我在 netbeans 8.1 下进行编码,我使用的是 for 循环,我很想知道 IDE 会建议什么代码格式化,所以我原来的循环是:

    List<Produit> produits = pjc.findProduitEntities();
    for (Produit produit : produits) {
        System.out.println("p ="+produit.getTitre());
        observableArrayList.add(new FXProduit(produit));
    }

最后我得到了两个建议,我想了解它们是相同还是存在一些性能或内存管理差异。

第一个建议被命名为use functional operation based on lambda expression

    List<Produit> produits = pjc.findProduitEntities();
    produits.stream().map((produit) -> {
        System.out.println("p ="+produit.getTitre());
        return produit;
    }).forEach((produit) -> {
        observableArrayList.add(new FXProduit(produit));
    });

第二个使用inner class paradigm

    List<Produit> produits = pjc.findProduitEntities();
    produits.stream().map(new Function<Produit, Produit>() {
        @Override
        public Produit apply(Produit produit) {
            System.out.println("p ="+produit.getTitre());
            return produit;
        }
    }).forEach((produit) -> {
        observableArrayList.add(new FXProduit(produit));
    });

【问题讨论】:

  • @Omore 那很有帮助,你的评论就是答案
  • 感谢继续学习。

标签: java arraylist collections lambda


【解决方案1】:

匿名类版本最不吸引人,因为它会在每次需要垃圾收集的调用时创建一个新类和新实例。

可以使用peek()、并行流和方法引用来清理和改进流版本:

pjc.findProduitEntities().parallelStream()
    .peek(produit -> System.out.println("p ="+produit.getTitre()))
    .map(FXProduit::new)
    .forEach(observableArrayList::add);

我假设并行处理是可以的,因为对象最终处于可观察的上下文中,顺序没有区别。即使没有并行流(即只使用.stream()),代码仍然干净很多。

【讨论】:

  • 谢谢波西米亚人,我从这个答案中学到了很多东西,我想在谷歌中搜索解释“::”如何工作的教程,但不幸的是我不知道我们如何称呼它,在乍一看这倒是蛮像倒影的感觉。 do new 将调用与参数匹配的构造函数,这也感觉像是 Spring 1 的思维方式(也许我不正确,因为我缺乏英语)。请为我的研究提供关键字
  • ::method reference。是的,构造函数也可以使用::new 来引用,是的.map() 方法需要一个Function,它接受流的元素类型并返回其他内容,这就是接受元素的构造函数所做的。
  • 即使顺序无关紧要,但这并不意味着observableArrayList.add 是线程安全的。事实上,这不太可能。结合这一事实,这个操作很可能根本不会从并行处理中受益……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-08
相关资源
最近更新 更多