Pattern to split string and store in HashMap Java 8

java 8 split string to map
java 8 split string> stream
how to split a string by position in java
how to split a string in java with delimiter
split string into hashmap java
how to divide a string into substrings in java
java 8 split string and iterate
string split java

I want to split the below string and store it in a HashMap:

String currentString= "firstName-lastName-rollNum-departmentNum=firstName1-lastName1-rollNum1-departmentNum1"; 

I want my output to be store in map, like first string before hyphen (-)(firstName) and first string after (=)(firstName1),......... i.e.,


Below code doesn't work for my pattern:

Map<String,String> mapVal= null;
mapVal = Pattern.compile("\\s*=\\s*")
                .map(s -> s.split("-", 2))
                .collect(Collectors.toMap(a -> a[0], a -> a.length>1? a[1]: ""));

Once I split the string I don't understand how I can get my required values together as shown above. I apologize if you don't get my question.

Thanks in advance !!

A simpler approach is to just use split with standard arrays.

String[] keyValues = currentString.split("=", 2);
String[] keys = keyValues[0].split("-");
String[] values = keyValues[1].split("-", keys.length);
Map<String, String> map = IntStream.range(0, keys.length).boxed()
        .collect(Collectors.toMap(i -> keys[i], i -> values[i]));

There's no error checking in this but hopefully it'll give you the general idea.

split string and store it into HashMap java 8, Unless Splitter is doing any magic, the getTokenizeString method is obsolete here. You can perform the entire processing as a single operation  The string split() method in Java splits a given string around matches of the given regular expression. Learn more with different examples.

As shown in this answer, a plain array based operation may be much simpler here.

But if you insist on a Stream solution, it may look like

Map<String,String> mapVal= Stream.of(currentString)
    .map(s0 ->"\\s*=\\s*", 2))
        .map(s1 -> s1.split("-")).toArray(String[][]::new))
    .flatMap(a -> IntStream.range(0, a[0].length)
        .mapToObj(i -> new String[]{ a[0][i], i < a[1].length? a[1][i]: "" }))
    .collect(Collectors.toMap(a -> a[0], a -> a[1]));

Java split String: How to split a String into tokens with , How do I split a string into number of substrings? There are many ways to split a string in Java. The most common way is using the split() method which is used to split a string into an array of sub-strings and returns the new array. 1. Using String.split The string split() method breaks a given string around matches of the given regular expression. There are two variants of split() method in Java:

Another solution :

String[] arr = Arrays.toString(currentString.split("="))
                     .replaceAll("[\\[\\]]", "").replaceAll(",", "-")

Map<String, String> collect = IntStream.range(0, arr.length / 2).boxed()
                 .collect(Collectors.toMap(i -> arr[i], i -> arr[i + arr.length / 2]));

Here we split the string first based on =, then we use the .toString() to remove all occurrences of ] and[ from the String. Now we replace , with - so we can split the resulting String based on -

After the first statement the array arr looks like :

[firstName, lastName, rollNum, departmentNum, firstName1, lastName1, rollNum1, departmentNum1]

Now all we need to do is to iterate over the resulting array(arr) upto the mid-point(arr.length / 2) and map it using Collectors.toMap

2 ways to Split String with Dot (.) in Java using , objects (Values) and each such object is identified by an Integer object (Key). Returns a literal pattern String for the specified String. This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern. Metacharacters or escape sequences in the input sequence will be given no special meaning.

Other way would be like this:

Pattern pattern = Pattern.compile("\\s*=\\s*");
int index = currentString.indexOf("=");
Map<Boolean, List<String>> map = pattern
            .flatMap(s -> Stream.of(s.split("-")))
            .collect(partitioningBy(s -> currentString.indexOf(s) > index));

this step result is:

  false=[firstName, lastName, rollNum, departmentNum],

  true=[firstName1, lastName1, rollNum1, departmentNum1]

and then convert previous result to final result:

IntStream.range(0, map.get(true).size())
            .collect(toMap(i -> map.get(false).get(i), i -> map.get(true).get(i)));

Java Hashmap - Tutorial With Examples, Learn how to split a comma-separated String into a list of Strings and Java 8 has introduced a new Stream API that lets us process data in a  HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs.

public static Map<String, String> toMap(String str) {
    String[] arr = str.split("[-=]");
    Map<String, String> map = new LinkedHashMap<>();

    for (int i = 0, j = arr.length / 2; j < arr.length; i++, j++)
        map.put(arr[i], arr[j]);

    return map;

String Operations with Java and Stream API, The StrSplit() method splits a String into an array of substrings. Learn how to split a string in Java with examples in this tutorial. Here if we want all individual strings, the best possible pattern would be to split it based on the comma. a Java String to Integer · 25) HashMaps in Java · 26) Command-line  A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

How to Split a String in Java: Learn with Example, how to split a string into multiple strings in java Pattern to split string and store in HashMap Java 8, A simpler approach is to just use split with standard arrays. That would probably work, for only one occurrence of each word. You're on the right track So split the text up into words, probably using text.split and a regex to split on whitespace.

How to split strings and store into a hashmap of strings in java, Use the Guava Splitter class to split strings. Review splitToList and We can pass a CharMatcher or a regular expression pattern—or just a character. List: SplitToList Java program that uses Splitter with HashMap import java.util.​HashMap  Java 8 has come with the following improvements/changes of HashMap objects in case of high collisions. The alternative String hash function added in Java 7 has been removed. Buckets containing a large number of colliding keys will store their entries in a balanced tree instead of a linked list after certain threshold is reached.

Java Splitter Examples: split, splitToList, A part of Java 8 streams is the map() facility which can map one value to Here is an example of a multi-line function which splits a String and String[] arr = pattern.split(x); Process data using Java 8 Streams and store in Collections Introduction A HashMap is a map of keys to values which uses a  Pattern Programs in Java. Star Patterns in Java; Numeric Patterns; Character Patterns; Let’s get started. :-) Star Patterns in Java. First, let us begin with the basic and the commonly asked pattern program in Java i.e Pyramid. 1. Pyramid Program * * * * * * * * * * * * * * * Let’s write the java code to understand this pattern better.