in this tutorial im going to explain how to split strings of following type type so that we can use them as key value in hash map
so our string is in this format
we have continuous string contain authors and their corresponding countries what we have to do first is split the string using .split();. it returnes an array string
again splitting that using delimer : and then add the values in to map
below is the full code
package stringmanipulation;
import java.util.HashMap;
import java.util.Map;
public class Stringtomap {
public static void main(String[] args) {
String name = "nikos Kazantzakis:Greece, nikos Kazantzakis:Greece, jersy kosinski:Poland,valmiki:india,shakessphere:England,jamcejoyce:ireland";
String[] name1 = name.split(",");
System.out.println("printing the array");
printArray(name1);
for (String name2 : name1) {
String[] name3 = name2.split(":");
Map<String, String> countrylist = new HashMap<String, String>();
countrylist.put(name3[0], name3[1]);
System.out.println(countrylist);
}
}
public static void printArray(String[] name1) {
for (String print : name1) {
System.out.println(print);
}
}
}
running the program will give the output
so our string is in this format
String authors = "nikos Kazantzakis:Greece, nikos Kazantzakis:Greece, jersy
kosinski:Poland,valmiki:india,shakessphere:England,jamcejoyce:ireland";
String[] countries = authors.split(",");
the result would be an array of string
countries[0] = nikos Kazantzakis:Greece;
countries[1] = jersy
kosinski:Poland again splitting that using delimer : and then add the values in to map
below is the full code
package stringmanipulation;
import java.util.HashMap;
import java.util.Map;
public class Stringtomap {
public static void main(String[] args) {
String name = "nikos Kazantzakis:Greece, nikos Kazantzakis:Greece, jersy kosinski:Poland,valmiki:india,shakessphere:England,jamcejoyce:ireland";
String[] name1 = name.split(",");
System.out.println("printing the array");
printArray(name1);
for (String name2 : name1) {
String[] name3 = name2.split(":");
Map<String, String> countrylist = new HashMap<String, String>();
countrylist.put(name3[0], name3[1]);
System.out.println(countrylist);
}
}
public static void printArray(String[] name1) {
for (String print : name1) {
System.out.println(print);
}
}
}
running the program will give the output
No comments:
Post a Comment