How to get all texts between the + sign and put them inside an HashMap in Java
As shown in the following example: product1 + product2 + product3 + product4 + product5
I need to put all the products in an HashMap
I'm assuming "product1 + product2 + product3 + product4 + product5" is a string.
You could iterate over the string using a CharacterIterator and only grab the characters if they are not a "+" or a " " (space), then when you hit a plus sign or a space then store the built up string in the HashMap:
HashMap<String, String> productsHashMap = new HashMap<String, String>();
static void productsToHashMap(String str) {
CharacterIterator it = new StringCharacterIterator(str);
String product = "";
while (it.current() != CharacterIterator.DONE) {
if (it.current() != " " && it.current() != "+") {
product += it.current();
}
else {
this.productsHashMap.put("KEY_YOU_WANT", product);
product = "";
}
}
}
Sorry if I got any of the syntax wrong, I haven't done Java in awhile. Also there are other ways of iterating over a string if you prefer doing it a different way you can see some ways here: https://www.geeksforgeeks.org/iterate-over-the-characters-of-a-string-in-java/