Is Hashmap possible with various values?

Asked

Viewed 345 times

1

I need to fill a bank like this:

Milk 50 kcal 20 proteins 120 Carbo etc.

I got to do with hashmap, but I can only use one key for a value, it would have to do with various values, or another way that can do it without being 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);

1 answer

3


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

import java.util.*;

class Main {
    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;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I haven’t noticed if the code has other problems.

Browser other questions tagged

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