-2

String str = "id1;;name1 || id2;;name2 || id3;;name3||";

into id1 name1 ...and then store it in hashmap as id1 - key , name1- value id2 - key , name2 - value ......

Adil
  • 57
  • 3
  • 10

2 Answers2

1

One way to reach your goal is to use a StringTokenizer.

Code example:

public static void main(String[] args) {
    String input = "id1;;name1 || id2;;name2 || id3;;name3||";
    Map<String, String> map = new HashMap<>();
    // You have to split two times
    for (String outer : splitBy(input, " || ")) {
        List<String> inner = splitBy(outer, ";;"); // for example: outer="id1;;name1"
        // Make sure, you have two inner input-elements
        if (inner.size() == 2) {
            String key = inner.get(0); // First element of List = Key
            String value = inner.get(1); // Second element of List = Value
            map.put(key, value);
        }
    }
}

private static List<String> splitBy(String toSplit, String delimiter) {
    List<String> tokens = new ArrayList<>();
    StringTokenizer tokenizer = new StringTokenizer(toSplit, delimiter);
    while (tokenizer.hasMoreTokens()) {
        tokens.add(tokenizer.nextToken());
    }
    return tokens;
}

Also take a look at this: Scanner vs. StringTokenizer vs. String.Split

Community
  • 1
  • 1
Manuel Seiche
  • 221
  • 1
  • 5
-1

for this particular case you should do something like this:

    Map<String, String> yourHashMap = new HashMap<String, String>();
    String input = "id1;;name1 || id2;;name2 || id3;;name3||";
    // "\" is special character so it need an escape 
    String[] yourStrings = input.split("\\|\\|");
    String[] hashObject = new String[2];
    for (int i = 0; i <= yourStrings.length - 1; i++) {
        //fist you have to remove the whitespaces
        yourStrings[i] = yourStrings[i].replaceAll("\\s+", "");
        hashObject = yourStrings[i].split(";;");
        yourHashMap.put(hashObject[0], hashObject[1]);
    }

Your input string have a strange format, I recommend you to change it.

  • This doesnt compile in any way. a) ``String[] hashObject = "";``, b) ``yourStrings.replaceAll("\\s+","");`` (an array does not have a replaceAll method, also you dont assign the new value to anything) – f1sh Mar 29 '16 at 14:30
  • You are right about "a)", I'm sorry for that, but "b)" is working well, string have replaceAll since v1.4 – Vasile Adrian Brusturean Mar 30 '16 at 06:03
  • No, it's not working well. You still need to assign the new value to the variable. Strings are immutable in java. – f1sh Mar 30 '16 at 07:01