Transform Set<Integer> into Set<String>

Asked

Viewed 294 times

4

I need to store a Set<Integer> within a sharedpreferences, however it only accepts Set<String>, has how to make this conversion ?

            Set<Integer> checados = group.getCheckedIds();
            prefeditor.putStringSet("cardio_dias", checados); <- So aceita Set<String> aqui

3 answers

5


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

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());
    }
}
  • 1

    Or in place of the arrow, Integer::toString

  • 2

    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

  • 1

    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...

0

Set<String> checadosStrings = new HashSet<String>();
for (Integer checado : checados) {
    checadosStrings.add(checado.toString());
}
  • 3

    Could you make it explicit where your answer differs from Isac’s? I didn’t see any additions to her answer, not to mention that she doesn’t explain anything, just displays a code that works

Browser other questions tagged

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