0

I am having a string which has some | delimited value

He run|running|runned quickly, then he|she goes for practice

what is the possible way to place the save the | separated value in Hashmap Map<Integer , List<String>> so that map store for first

 1 -> ["run","running","runned"]
 2 -> ["he","she"]

How can it be achieved. What is the best to split this string and save the value in Map.

Peter Walser
  • 15,208
  • 4
  • 51
  • 78
Beginner
  • 145
  • 7
  • 1
    What have you tried so far? Do you already know there is a method named [`split`](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/String.html#split(java.lang.String)) in the String class? – Hulk Jul 12 '21 at 12:22
  • Does this answer your question? [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Hulk Jul 12 '21 at 12:24

1 Answers1

1

Try this:

String text = "He run|running|runned quickly, then he|she goes for practice";

// match all the parts which are sequences of words delimited by |
Matcher matcher = Pattern.compile("(\\w+(?:\\|\\w+)+)").matcher(text);

Map<Integer, List<String>> map = new HashMap<>();

// add matches as long as we find any.
while (matcher.find()) {
    map.put(map.size() + 1, 
    // split matches by | and convert them to a list
    Arrays.stream(matcher.group(1).split("\\|")).collect(Collectors.toList()));
}

Output:

map.forEach((k, v) -> 
    System.out.printf("%s = %s\n", k, v.stream().collect(Collectors.joining(","))));

yields:

1 = run,running,runned
2 = he,she
Peter Walser
  • 15,208
  • 4
  • 51
  • 78
  • Thanks @Peter Walser the main issue was I am not able to write the regex can you please share some link where I can learn how to create regex. – Beginner Jul 12 '21 at 12:43
  • https://www.vogella.com/tutorials/JavaRegularExpressions/article.html is a good start, and the Javadoc for `Pattern`: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Pattern.html. https://regex101.com/ is really useful as a learning playground. – Peter Walser Jul 12 '21 at 13:20
  • Thanks @Peter Walser – Beginner Jul 12 '21 at 16:27