Mohammed Housseyn Taleb
Mohammed Housseyn Taleb

Reputation: 1828

Is there any differences between this two ways of looping and which one is preferable to be used?

I was coding under netbeans 8.1 I was using a for loop and I was curious to see what will the IDE suggest as code formating, so my original loop was :

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

I got finally two suggestion that I want to understand if they are the same or there is some performance or memory management differences.

the first suggestion was named 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));
    });

the second one uses the 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));
    });

Upvotes: 0

Views: 55

Answers (1)

Bohemian
Bohemian

Reputation: 425003

The anonymous class version is the least attractive, because it creates a new class and new instances with every invocation that require garbage collection.

The stream version can be cleaned up and improved considerably using peek(), parallel stream and method references:

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

I have assumed that parallel processing is OK, since the objects end up in an observable context, in which order makes no difference. Even without the parallel stream (ie just using .stream()) the code is still a lot cleaner.

Upvotes: 1

Related Questions