What is this? private List<Map<String, Object>> expenses;

Asked

Viewed 839 times

3

A list of maps? Seriously I was scared of this. 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;
 }
}
  • 1

    That’s right a map list...

  • This method could very well return only the Map created, since what he is creating is a list with a single element, and therefore there is not much sense that it is a list to begin with. I would like to know where this method is used to understand whether there is sense in it being a list of maps or whether it should be something else. Where this method is used?

  • Was the answer helpful to you? Don’t forget to mark it so it can be used if someone has a similar question!

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 your example:

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

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

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);

Browser other questions tagged

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