Transform SetInteger into SetString

4

I need to store a Set<Integer> within a sharedpreferences, but it only accepts Set<String> , can you do that conversion?

            Set<Integer> checados = group.getCheckedIds();
            prefeditor.putStringSet("cardio_dias", checados); <- So aceita Set<String> aqui
    
asked by anonymous 23.11.2017 / 23:27

3 answers

5

You can simply use a loop / loop that passes all elements and converts them one by one to the type you want, thus creating a new loop% of that type. The conversion to Set is done by calling String and back to integer doing with toString() .

Save Integer.parseInt()

Set<Integer> ints = new HashSet<>(); //o seu Set

Set<String> intsEmString = new HashSet<>();
for (Integer i : ints){
    intsEmString.add(i.toString()); //guardar a representação em String de cada um
}

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet("meu_set", intsEmString); //guardar o novo Set<String>
editor.commit();

Read Set

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);

//ler o Set<String> guardado
Set<String> intsEmString = sharedPref.getStringSet("meu_set", null); 
Set<Integer> ints = new HashSet<>(); //criar o novo que vai receber os valores

if (intsEmString != null){
    for(String s : intsEmString){
        ints.add(Integer.parseInt(s)); //converter de volta cada um com parseInt
    }
}

//utilizar o Set<Integer> restaurado
    
24.11.2017 / 00:46
4

With java8, you can use the stream:

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class Main {

    public static void main(String args[]) {
        Set<Integer> checados = new HashSet<>();
        Set<String> checadosString = checados.stream().map(inteiro -> inteiro.toString()).collect(Collectors.toSet());
    }
}
    
24.11.2017 / 03:40
0
Set<String> checadosStrings = new HashSet<String>();
for (Integer checado : checados) {
    checadosStrings.add(checado.toString());
}
    
24.11.2017 / 01:46