Home > front end >  How do I convert a multiple strings into a set of strings?
How do I convert a multiple strings into a set of strings?

Time:10-04

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?

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.

CodePudding user response:

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);
    }
    
}

CodePudding user response:

I would do it simply like that:

    String a = "123, 541, 123";
    String b = "527";
    String c = "234, 876";
    
    List<String> all = Arrays.asList((a   ","   b   ","   c).split(","));
    Set<String> result = new HashSet<>();
    for (String s : all) {
        result.add(s.trim());
    }

    System.out.println(result); // [123, 541, 234, 876, 527]

But I would try to the change the situtation that you have 3 different strings in the first place. Input should be an Array of Strings, so you don't have to care, if it is 1 or 37238273 different strings.

But without knowing where you have these 3 strings from, why they are 3 variables, hard to advice how to actually optimize that.

CodePudding user response:

Something like this:

List<String> all = Arrays.asList((a   ", "   b   ", "   c).split(", "));

CodePudding user response:

A simple approach with Stream flat-mapping:

Set<String> result = Stream.of(a, b, c)
        .map(s -> s.split(", "))
        .flatMap(Arrays::stream)
        .collect(Collectors.toSet());

CodePudding user response:

try it plz.

Set<String> result = new HashSet<>();
for (String s : (a   ","   b   ","   c).split(",")) {
    result.add(s.trim());
}

CodePudding user response:

In Java 9:

import java.util.Set;
Set<String> result = Set.of("123", "541", "527", "234", "876");
  •  Tags:  
  • java
  • Related