2

What do I have

I have three classes. Main.java, Producto.java, and Supermercado.java.

  • Main.java contains the main.
  • Producto.java the product structure I want to print in my list.
  • Supermercado.java is a Singleton Pattern which represents the supermarket where my List is placed.

The code

I will show you guys only the code I think is related to the question, if you need more information please do not hesitate to ask.

Main.java

// Instanciar productos
Producto p1 = new Producto("Sal 100gr",  LocalDate.now(), 0.5f, 1);
Producto p2 = new Producto("Pimienta 25gr",  LocalDate.now(), 0.2f, 1);
Producto p3 = new Producto("Sal 1kg",  LocalDate.now(), 2, 1);
Producto p4 = new Producto("Te limón", LocalDate.now(), 3.5f, 2);
Producto p5 = new Producto("Azucar 1kg", LocalDate.now(), 2, 1);
Producto p6 = new Producto("Azucar 5kg", LocalDate.now(), 10, 1);
Producto p7 = new Producto("Xilitol 1kg", LocalDate.now(), 15, 1);
Producto p8 = new Producto("Xilitol 1kg", LocalDate.now(), 15, 1);

// Añadir productos a la lista del super
Supermercado.getSupermercado().addProducto(p1);
Supermercado.getSupermercado().addProducto(p2);
Supermercado.getSupermercado().addProducto(p3);
Supermercado.getSupermercado().addProducto(p4);
Supermercado.getSupermercado().addProducto(p5);
Supermercado.getSupermercado().addProducto(p6);
Supermercado.getSupermercado().addProducto(p7);
Supermercado.getSupermercado().addProducto(p8);

// Printing the list
System.out.println("\nLista productos.");
Supermercado.getSupermercado().printListaProductos();

// Printing distinct items (do not repeat xilitol plz)
System.out.println("\nLista de productos sin repetir.");
Supermercado.getSupermercado().printListaProductosSinRepetir();

Supermercado.java

// Printing the list
public void printListaProductos() {
    listaProducto.stream()
        .forEach(p -> System.out.println("Producto " +p.getNombre() 
            + '\t' + "Precio " + p.getPrecio() + "€"
            + '\t' + "Caducidad " + p.getFechaCaducidad()));
}

// Printing distinct items (do not repeat xilitol plz)
public void printListaProductosSinRepetir() {
    listaProducto.stream()
        .distinct()
        .forEach(p -> System.out.println("Producto " +p.getNombre() 
            + '\t' + "Precio " + p.getPrecio() + "€"
            + '\t' + "Caducidad " + p.getFechaCaducidad()));
}

Producto.java

private String nombre;
private int seccion;
private LocalDate fechaCaducidad;
private float precio;

// constructor
public Producto(String pNombre, LocalDate pFechaCaducidad, float pPrecio, int pSeccion) {
    this.nombre = pNombre;
    this.fechaCaducidad = pFechaCaducidad;
    this.precio = pPrecio;
    this.seccion = pSeccion;
}

public LocalDate getFechaCaducidad() {
    return this.fechaCaducidad;
}

public float getPrecio() {
    return this.precio;
}

public int getSeccion() {
    return this.seccion;
}

public String getNombre() {
    return this.nombre;
}

The Output

Lista productos.
Producto Sal 100gr  Precio 0.5€ Caducidad 2016-05-27
Producto Pimienta 25gr  Precio 0.2€ Caducidad 2016-05-27
Producto Sal 1kg    Precio 2.0€ Caducidad 2016-05-27
Producto Te limón   Precio 3.5€ Caducidad 2016-05-27
Producto Azucar 1kg Precio 2.0€ Caducidad 2016-05-27
Producto Azucar 5kg Precio 10.0€    Caducidad 2016-05-27
Producto Xilitol 1kg    Precio 15.0€    Caducidad 2016-05-27
Producto Xilitol 1kg    Precio 15.0€    Caducidad 2016-05-27

Lista de productos sin repetir.
Producto Sal 100gr  Precio 0.5€ Caducidad 2016-05-27
Producto Pimienta 25gr  Precio 0.2€ Caducidad 2016-05-27
Producto Sal 1kg    Precio 2.0€ Caducidad 2016-05-27
Producto Te limón   Precio 3.5€ Caducidad 2016-05-27
Producto Azucar 1kg Precio 2.0€ Caducidad 2016-05-27
Producto Azucar 5kg Precio 10.0€    Caducidad 2016-05-27
Producto Xilitol 1kg    Precio 15.0€    Caducidad 2016-05-27
Producto Xilitol 1kg    Precio 15.0€    Caducidad 2016-05-27

The Problem

Clearly, the .distinct() code in printListaProductosSinRepetir() method is not working for me. It should display this:

Lista de productos sin repetir.
Producto Sal 100gr  Precio 0.5€ Caducidad 2016-05-27
Producto Pimienta 25gr  Precio 0.2€ Caducidad 2016-05-27
Producto Sal 1kg    Precio 2.0€ Caducidad 2016-05-27
Producto Te limón   Precio 3.5€ Caducidad 2016-05-27
Producto Azucar 1kg Precio 2.0€ Caducidad 2016-05-27
Producto Azucar 5kg Precio 10.0€    Caducidad 2016-05-27
Producto Xilitol 1kg    Precio 15.0€    Caducidad 2016-05-27

Without the extra Xilitol 1kg. The items shouldn't repeat.

Why do I need this

I am trying to learn how Java 8 works with the Lambda-expressions. So I am building myself some examples for this. The thing is that .distinct() is not working. I couldn't find this solution in SO. Thanks in advance.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
Jose Serodio
  • 1,390
  • 3
  • 17
  • 31

2 Answers2

3

You should override equals and hashCode methods from object class in order to make this work here is an example. Add in your Producto.java the following code.

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((nombre == null) ? 0 : nombre.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Producto other = (Producto) obj;
    if (nombre == null) {
        if (other.nombre != null)
            return false;
    } else if (!nombre.equals(other.nombre))
        return false;
    return true;
}
Jose Serodio
  • 1,390
  • 3
  • 17
  • 31
Priyamal
  • 2,919
  • 2
  • 25
  • 52
  • 2
    Unnecessarily complicated. You get the same result using `public int hashCode() { return 31+Objects.hashCode(nombre); }` and `public boolean equals(Object obj) { return this == obj || obj!=null && getClass()==obj.getClass() && Objects.equals(nombre, ((Producto)obj).nombre); }` – Holger May 27 '16 at 15:49
  • @Holger it worked too! Just wanted to say that the above code is the one `Eclipse` writes with `right click -> source -> Generate hashcode() and equals()...`. But I'll be using your code, since It's shorter and seems easier. Thank you. – Jose Serodio May 28 '16 at 08:57
1

You should override the equal function of the Producto

the distinct() function removes the duplicated element depending on the equal() for the object

when you do not override the equal() function, the default behavior is to compare with the object reference address

Javy
  • 944
  • 5
  • 9