How to do for every time you pass "true", it print the entire instantiated object?

Asked

Viewed 110 times

4

import java.util.ArrayList;

public class Loja {

    private ArrayList<Produto> ListaDeProdutos = new ArrayList<>();

    public void cadastrarProduto(Produto produto){
        ListaDeProdutos.add(produto);
    }

    public void listarProdutos(){
        ListaDeProdutos.forEach(P -> System.out.println(P.toString() + "\n"));
    }

    public void listarDiscos(){
        ListaDeProdutos.forEach(P -> System.out.println(P.toString().contains("Banda"))); 
        //eu quero que ele imprima todo o conteúdo setado, não apenas "true"
    }
}

Testing

public class Teste {
    public static void main(String[] args) {
        Loja l1 = new Loja();
        l1.cadastrarProduto(new Livro("Java - Use A cabeça", 01, 120.00f, "Fulano de tal", "DevMasters", 400, "PROGRAMAÇÃO"));
        l1.cadastrarProduto(new Livro("LIVRO DE C", 02, 80.00f, "Deitel", "Dev Masters", 800, "PROGRAMAÇÃO"));
        l1.cadastrarProduto(new Livro("PYTHON", 03, 100.00f, "Lokão dazideia", "Dev Masters", 200, "PROGRAMAÇÃO"));
        l1.cadastrarProduto(new Disco("Back in Black", 04, 100.00f, "AC/DC", "Hard Rock", 15));
        l1.cadastrarProduto(new Disco("Sattelite", 05, 20.00f, "P.O.D.", "White Metal", 11));
        l1.cadastrarProduto(new Disco("Musashi", 06, 15.00f, "Rashid", "Rap", 14));    
        l1.listarDiscos();
    }
}

Exit

false
false
false
true
true
true

2 answers

7


The question does not give many details, but it would be something like this:

for (Produto produto : ListaDeProdutos ) {
    if (produto.nome.contains("Banda")) {
        System.out.println(produto.nome);
        System.out.println(produto.preco);
        System.out.println(produto.genero);
    }
}

I put in the Github for future reference.

I thought better to do. The use of stream may seem cute, but it is slower, has semantics different from the normal loop, although in this example does not cause problems, but has a number of implications that almost nobody understands and the normal is to cause problems, and there is almost always no real gain except, in some cases, leave a code with fewer lines, which is not always good. In which case it wouldn’t actually happen, so it’s just a waste of time.

Also don’t use the tostring() for that reason, it makes no sense to create something of general logic to meet a specific requirement. It is an abuse to use it to format data, even worse to have a debugging function used with complexity O(n).

Actually there may be a conceptual error there. I don’t know if Loja should print something, it process is ok, print is already a platform detail where it runs and maybe should be manipulated elsewhere. For exercise you can do so, but know that in real code is not how you do it.

  • I’m sorry for the lack of detail, it was the rush. But you think I need to describe more?

  • I could have given a better answer if I had more information.

  • Your reply was excellent. Sorry for the inexperience.

  • public void listarDiscos(){&#xA; for (Produto produto : ListaDeProdutos ) {&#xA; if (produto.toString().contains("Banda")) {&#xA; System.out.println(produto.toString());&#xA; }&#xA; &#xA; }&#xA; }

  • I was able to adapt to my problem and it worked. :)

  • It didn’t work, it worked, right it’s something else, you’re abusing the ToString(): https://answall.com/q/212754/101

  • True. How could I then?

  • 3

    Like I did....

Show 3 more comments

3

The method contains returns a boolean, so the code only prints true or false. If you want to print products that meet a condition, you can make a for simple as suggested by Maniero.

Another option is to turn the list into one stream and use filter to filter the products that satisfy their condition and then print them:

ListaDeProdutos.stream()
    // filtrar produtos
    .filter(p -> p.toString().contains("Banda"))
    // imprimir
    .forEach(System.out::println);

But if you want to filter the products by a specific type (in case, Disco), could use instanceof to test whether the product is an instance of Disco:

ListaDeProdutos.stream()
    // filtrar produtos que são Disco
    .filter(p -> p instanceof Disco)
    // imprimir
    .forEach(System.out::println);
  • It was exactly what I wanted. Thank you very much. So I do not abuse the toString()

  • 1

    @Emersonaraujo in this case is abusing the toString() and of streams.

  • I’m still beginning to understand about POO and Java, sorry if I’m missing too much.

  • 1

    @Emersonaraujo In fact, it’s best to use class attributes (such as the name, type, etc.) to verify what it represents, rather than toString(). Another tip is to read the code conventions - variable names, for example, should start with lower case letter, so it would be better to have listaDeProdutos (with l lower case). With L uppercase sounds like a class name and may confuse others already used to such conventions - see more in https://answall.com/q/153540/112052

  • I will read yes, thanks for the tips.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.