Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide two String into substrings and pair them

I am looking for interesting solutions for this problem :

String key = "1;2;3;4";
String value = "Value1;Value2;Value whitespace;"

Now ';' devides each value from another. The same symbol ';' devides the keys also.

Now I want to end up with :

{"1" : "Value1", "2" : "Value2", "3" : "Value whitespace", "4" : null}

Of course if the values were more then the keys then the null should be no the left side of the pair (null: "Value5").

I made a pretty complecated solution to this problem using char arrays but is one big FOR with many cases and stuff.(it is O(n)). So I am curious to see a regex or substring solution or something that not includes big loop.

EDIT: Mine solution :

private List<ExampleObject> getExampleObjects(String key , String value) {
    // s
    if (key  == null || value == null) {
        return new ArrayList<ExampleObject>();
    }

    List<ExampleObject> exampleObjects = new ArrayList<ExampleObject>();

    char[] keyToCharArray = key.toCharArray();
    char[] valueToCharArray = value.toCharArray();

    StringBuilder name = new StringBuilder();
    StringBuilder value = new StringBuilder();

    boolean nameCompleted = false;
    boolean valueCompleted = false;

    for (int i = 0, j = 0; i < keyToCharArray.length || j < valueToCharArray.length;) {
        if (!nameCompleted) {
            char a = ' ';
            try{
                 a = keyToCharArray[i];
            } catch(Exception e){
                 a = ';';
                // throw : VALES and key  not match. More key  then value
                //throw(e);
            }

            if (a == ';' ) {
                nameCompleted = true;
            } else if (!(i + 1 < keyToCharArray.length)){
                name.append(a);
                nameCompleted = true;
            }   else {
                name.append(a);

            }
            i++;
        }
        if (!valueCompleted) {

            char a = ' ';
            try{
                 a = valueToCharArray[j];
            } catch(Exception e){
                 a = ';';
                // throw : VALES and key  not match. More value then key 
                //throw(e);
            }

            if (a == ';') {
                valueCompleted = true;
            } else if(!(j + 1 < valueToCharArray.length)) {
                value.append(a);
                valueCompleted = true;
            } else {
                value.append(a);
            }
            j++;
        }
        if (nameCompleted && valueCompleted) {
            exampleObjects.add(new ExampleObject(name.toString(), value.toString()));
            name.setLength(0);
            value.setLength(0);
            nameCompleted = false;
            valueCompleted = false;
        }
    }
    return exampleObjects;
}

Where ExampleObject.class has fields key and value.

like image 527
Lazar Lazarov Avatar asked Feb 14 '26 06:02

Lazar Lazarov


2 Answers

I've come up with a solution to your problem:

Output

{"1" : "Value1", "2" : "Value2", "3" : "Value whitespace", "4" : "null"}       

Code

public class HelloWorld{

     public static void main(String []args){
        String key = "1;2;3;4";
        String value = "Value1;Value2;Value whitespace;";

        String[] keyArr = key.split(";");
        String[] valueArr = value.split(";");

        String finalJSON = "{";
        for(int i=0; i<(keyArr.length > valueArr.length ? keyArr.length : valueArr.length); i++) {

            try {
                finalJSON += "\"" + keyArr[i] + "\"";
            }
            catch(ArrayIndexOutOfBoundsException e) {
                finalJSON += "\"null\"";
            }

            finalJSON += " : ";

            try {
                finalJSON += "\"" + valueArr[i] + "\"";
            }
            catch(ArrayIndexOutOfBoundsException e) {
                finalJSON += "\"null\"";
            }
            if(i!=(keyArr.length > valueArr.length ? keyArr.length : valueArr.length) - 1) 
                finalJSON += ", ";
        }
        finalJSON += "}";

        System.out.println(finalJSON);
     }
}
like image 138
Raman Sahasi Avatar answered Feb 16 '26 21:02

Raman Sahasi


Java 8:

String key = "1;2;3;4";
String value = "Value1;Value2;Value whitespace;";
String[] keys = key.split(";", -2);
String[] values = value.split(";", -2);

Map<String, String> result = IntStream.range(0, keys.length).mapToObj(i->i).collect(Collectors.toMap(i->keys[i], i-> values[i]));
result.entrySet().forEach(e->result.put(e.getKey(), e.getValue().length()==0 ? null : e.getValue()));
like image 44
Marcin Szawurski Avatar answered Feb 16 '26 19:02

Marcin Szawurski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!