You can simply use a loop/loop that passes across all elements and converts them one by one to the type you want, thus creating a new one Set
of this type. Conversion to String
is made by calling the toString()
and back to the whole makes Integer.parseInt()
.
Guard the Set
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 the 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
Or in place of the arrow,
Integer::toString
– Jefferson Quesado
I tried to use it this way, but the compiler complains that the method is ambiguous: Ambiguous method Reference: Both toString() and toString(int) from the type Integer are eligible
– Fagner Fonseca
you’re right, I just remembered that I went through the same situation at work and I had to go to that solution with the arrow...
– Jefferson Quesado