Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I convert a multiple strings into a set of strings?

So I have following strings,

String a = "123, 541, 123"
String b = "527"
String c = "234, 876"

I would like to loop over these strings, split the string by "," and store it in a set of string so that I have such final output,

("123", "541", "527", "234", "876")

Any idea how I can achieve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried splitting the string but that results in Set<String[]> and not sure how to proceed with this since I am very new to this.

>Solution :

First, you need to separate strings in "a" and "c" variable. For that you can you can you split() method. You can try code below and adapt it in a way that fits your needs.

Set<String> strings = new HashSet<>();

String a = "123, 541, 123";
String b = "527";
String c = "234, 876";

private void addToSet(String stringNumbers) {
    
    for(String str : Arrays.asList(stringNumbers.split(","))) {
        strings.add(str);
    }
    
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading