Is it possible HashMap with several values?

1

I need to populate a bank like this:

  

Milk 50 kcal 20 proteins 120 carbo etc

hashmap , but I can only use a key for a value, I could do with multiple values, or some other way I can do this without using HashMap ?

Map<String, Integer> mapalimentos = new HashMap<>();
    mapalimentos.put("Maçã",60);
    mapalimentos.put("Melancia",75);
    mapalimentos.put("Banana",45);

    //Log.d(TAG, "addalimentosbanco: adicionou");


    for (final Map.Entry<String,Integer> entry : mapalimentos.entrySet()) {
        //Log.d(TAG, "addalimentosbanco: Nome: " + entry.getKey() +" Calorias: "+ entry.getValue());
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                Alimento alimento = realm.createObject(Alimento.class);
                alimento.setNome(entry.getKey());
                alimento.setCalorias(entry.getValue());
            }
        });
    }
    RealmResults<Alimento> results = realm.where(Alimento.class).findAll();
    Log.d(TAG, "addalimentosbanco: Result: " + results);
    
asked by anonymous 21.11.2017 / 16:44

1 answer

2

It's simple, create a class with the members you need to use, then make the value be this object with all members inside. Something like this (very simplified):

import java.util.*;

class Ideone {
    public static void main (String[] args) {
        Map<String, Alimento> mapalimentos = new HashMap<>();
        mapalimentos.put("Maçã", new Alimento(50, 10));
        mapalimentos.put("Melancia", new Alimento(30, 20));
    }
}

class Alimento {
    public Alimento(int calorias, int proteinas) {
        Calorias = calorias;
        Proteinas = proteinas;
    }
    int Calorias;
    int Proteinas;
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

I have not noticed if the code has other problems.

    
21.11.2017 / 17:09