What is this? private ListMapString, Object expenditures;

3

A list of maps? I seriously was scared of it. I've never seen this in my life ...

private List<Map<String, Object>> listarGastos() {
  gastos = new ArrayList<Map<String, Object>>();
  Map<String, Object> item = new HashMap<String, Object>();
 item.put("data", "04/02/2012");
 item.put("descricao", "Diária Hotel");
 item.put("valor", "R$ 260,00");
 item.put("categoria", R.color.categoria_hospedagem);
 gastos.add(item);

   return gastos;
 }
}
    
asked by anonymous 28.11.2016 / 05:27

1 answer

3

Yes, it is a list of maps. It allows you to insert a set of keys and values forming a structure like the one in your example:

[
  {"data": "04/02/2012"},
  {"descricao": "Diária Hotel"},
  {"valor": "R$ 260,00"},
  {"categoria": R.color.categoria_hospedagem}
]

In case you know what attributes are placed in Map it is more effective to create an object in the expected format. Make the code more readable and easier to work on.

It would be best represented by:

import java.time.LocalDate;

public class Item {

  private LocalDate data;
  private String descricao;
  private double valor;
  private String categoria;

  public LocalDate getData() {
    return data;
  }

  public void setData(LocalDate data) {
    this.data = data;
  }

  public String getDescricao() {
    return descricao;
  }

  public void setDescricao(String descricao) {
    this.descricao = descricao;
  }

  public double getValor() {
    return valor;
  }

  public void setValor(double valor) {
    this.valor = valor;
  }

  public String getCategoria() {
    return categoria;
  }

  public void setCategoria(String categoria) {
    this.categoria = categoria;
  }
}

And the use would be:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
List<Item> gastos = new ArrayList<>();
Item item = new Item();

item.setData(LocalDate.parse("04/02/2012", formatter));
item.setDescricao("Diária Hotel");
item.setValor(260.00);
item.setCategoria(R.color.categoria_hospedagem);
gastos.add(item);
    
28.11.2016 / 05:34