How to Split this String and store in HashMap - java

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
......

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

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.

Related

How can I get the number of count each item in association rules in java?

I want to get the number of count for each item that includes rules like that,
A==>B,C,D
B==>A,C
C==>B
In these rules,
I want to get like that A=2, B=3, D=1, C=3.
public class MDSRRC {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
File file =new File("C:\\sar.txt");
Scanner sc = new Scanner(file);
Set<String> leftSide = new HashSet<String>();
Set<String> rightSide = new HashSet<String>();
while (sc.hasNextLine()) {
String line=sc.nextLine();
String[] lineSplited = line.split("==>");
String[] leftStrings = lineSplited[0].split(",");
for (String string : leftStrings) {
leftSide.add(string);
}
String[] rightStrings = lineSplited[1].split(" ");
for (String string : rightStrings){
if (string.length() > 0 && string.charAt(0) == '#'){
break;
}
rightSide.add(string);
}
//System.out.println(rightSide);
}
}
}
As you are counting each character no matter if it is on the left or right side, you can use just one result structure. Datatype Set is nice if you just want to know the different kind of characters that occures but you also want the count so I suggest to change your result data type to a Map so you can keep a counter for every character.
So replace leftSide and rightSide by a single Map instance and for every character you encounter, check if it exists already in your Map. If so, add one to the value part of that entry, if not put the new character to the map with value 1.
File file = new File("D:\\sar.txt");
Scanner sc = new Scanner(file);
Map<String, Integer> resultMap = new HashMap();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] lineSplited = line.split("==>");
String first = lineSplited[0];
resultMap.putIfAbsent(first, 0);
resultMap.put(first, resultMap.get(first) + 1);
String[] right = lineSplited[1].split(",");
for (String a : right) {
resultMap.putIfAbsent(a, 0);
resultMap.put(a, resultMap.get(a) + 1);
}
}

How to get first and second character from String in multiple conditions

I have name String[] let suppose "Raj Kumar". Then the condition is that I want to get "R" from Raj and "K" from "Kumar" and if the text is "Raj" then I have to get "Ra" from "Raj". How do I do that below is the code I want to modify.
code:-
public static final String[] titles = new String[]{"Raj", "Niraj Kumar"};
for(int i = 0;i<titles.length;i++){
char firstChar = titles[i].charAt(0);
}
You this method
public String getShortName(String name){
String[] token=name.split(" ");
if(token.length>1){
String value="";
for(int i=0;i<token.length;i++){
value+=token[i].substring(0,1);
}
return value;
}else{
return token[0].length()>1?token[0].substring(0,2):token[0];
}
}
I have tested it, For array of names use this method in for loop
First, create this method to process each individual string in the array:
private static String processString(String string) {
String[] words = string.split(" ");
if (words.length == 1) {
return words[0].substring(0, 2);
} else {
return Arrays.stream(words).map(x -> Character.toString(x.charAt(0))).collect(Collectors.joining());
}
}
And then, stream the array and map each item using the method:
List<String> mapped = Arrays.stream(titles)
.map(YourEnclosingClass::processString)
.collect(Collectors.toList());
You can then print the values out like this:
mapped.forEach(System.out::println);
You can try like this :
public static final String[] titles = new String[]{"Raj", "Niraj Kumar"};
for(int i = 0;i<titles.length;i++){
if(titles[i].contains(" ")){
char firstChar = titles[i].charAt(0) + titles[i].split(" ")[1].charAt(0);
}else{
char firstChar = titles[i].charAt(0) + titles[i].charAt(1);
}
}
final String[] titles = new String[]{"Raj", "Niraj Kumar"};
for (int i = 0;i<titles.length;i++){
String shortChar;
String[] nameSplit = titles[i].split("\\s+");
if(nameSplit.length == 1) {
shortChar = nameSplit[0].substring(0,2);
} else {
shortChar = nameSplit[0].substring(0,1) + nameSplit[1].substring(0,1);
}
}
Here you'll get Ra and NK as output (Hoping that the name contains first and second name only)
Here is another way using stream API:
Arrays.stream(titles)
.map(title -> title.contains(" ") ?
Arrays.stream(title.split(" "))
.reduce("", (a, b) -> a + b.charAt(0)) :
title.substring(0, 2))
.forEach(result -> {
// do with result
});

Convert value in string into hashmap?

I have a string where i have multiple values. The key and value are separated by * and the whole value is separated by $.
Below is the example:
String agf = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
And now I want to put the value of this into hashmap in key value pair.
Below is the code i was using but didnt work for converting it into hashmap. Please guide.
String agf = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
String []tmp = StringUtils.split(agf,'*');
for (String v : tmp) {
String[] t = StringUtils.split(v,'$');
map.put(t[0], t[1]);
}
import java.util.HashMap;
import java.util.Map;
public class Parse{
public static void main(String ...args){
String agf = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
String [] split = agf.split("\\$");
Map<String,String> map = new HashMap<String,String>();
for(String temp : split){
String [] tempo = temp.split("\\*");
map.put(tempo[0],tempo[1]);
}
for(String mapkeys : map.keySet()){
System.out.println(mapkeys+" ::: "+map.get(mapkeys));
}
}
}
if you had multiple values for a given key then use this:
public static void main(String ...args){
String agf = "abc*pqr*gas$sfd*ghn$atr*mnb$tre*fgt";
String [] split = agf.split("\\$");
Map<String,String> map = new HashMap<String,String>();
for(String temp : split){
String [] tempo = temp.split("\\*");
StringJoiner sj = new StringJoiner(",");
for(int i = 1; i < tempo.length;i++){
sj.add(tempo[i]);
}
String value = sj.toString();
map.put(tempo[0],value);
}
for(String mapkeys : map.keySet()){
System.out.println(mapkeys+" ::: "+map.get(mapkeys));
}
}
Hope you found this helpful
Looking at your example string, you should be splitting first on $ (to get individual key value pairs) and then on * (to separate key and values)
Switch '*' and '$'.
String agf = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
String []tmp = StringUtils.split(agf,'$');
for (String v : tmp) {
String[] t = StringUtils.split(v,'*');
map.put(t[0], t[1]);
}
Use string.split("//$") and string.split("//*") as regex for your use case.
Full code :
String str = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
String[] entries = str.split("\\$");
Map<String, String> map = new HashMap<String, String>();
for (int i=0; i<entries.length; i++) {
String[] entry = entries[i].split("\\*");
map.put(entry[0], entry[1]);
}
System.out.println("Entries are -> " + map.entrySet());
String agf = "abc*pqr$sfd*ghn$atr*mnb$tre*fgt";
\\next array will contain such elements: "abc*pqr", "sfd*ghn", "atr*mnb", "tre*fgt"
String[] pairs = agf.split("\\$");
Map<String, String> map = new HashMap();
for (String pair: pairs) {
\\in first iteration next array will contain such elements: "abc", "pqr"
String[] t = pair.split("\\*");
\\just fill out map with data
map.put(t[0], t[1]);
}

How to initiate a String array?

I suddenly get struck to initiate String array in the part of a program. The idea is to read String input from the Scanner and make an array of String. I wrote it as following,
Scanner sc = new Scanner(System.in);
String parts [] ;
while(sc.hasNext() ){
String str = sc.nextLine();
// the str value suppose to be *1, 2, 3, 4, 5, 99, 1, 2, 3, 4, 5*
parts = new String[] { str.split(", ")}; // need correction
}
I actually need an Integer array, but, I would better do it in next iteration using
Ingeter.valueOf(str_value)
How to write properly the String array generation inside the while loop ?
split is already returning String[] array so simply assign it to your String parts [] reference:
parts = str.split(", ");
Seeing some confusion in comments, it may be more appropriate for you to use a List, rather than an array. Here's a working example:
List parts = new ArrayList();
while (sc.hasNext())
{
String str = sc.readLine();
for (String i : str.split(", "))
{
parts.add(Integer.valueOf(Integer.parseInt(i)));
}
}
I provided the entire solution below where you can get one single element which is not in a pair.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean bol = false;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
while(sc.hasNext() ){
String str = sc.nextLine();
for (String s: str.split(", ") ){
int t = Integer.valueOf(s);
map.put(t, map.containsKey(t) ? map.get(t) + 1 : 1);
}
}
if (bol){
for (Map.Entry<Integer, Integer> entry : map.entrySet() ){
if ( entry.getValue() == 1){
System.out.println(entry.getKey());
}
}
}
else {
Iterator it = map.entrySet().iterator();
while ( it.hasNext() ){
Map.Entry pair = (Map.Entry) it.next();
if ( pair.getValue() == 1 ){
System.out.println(pair.getKey());
}
}
}
}

split a string in java algorithm

I have the below string :
FIELD,KEY,0,AREA,2,3,4
I need to pick out the values of key and area and convert them to integer array .. e.g.
key = {0};
area = {2,3,4}
How could I achieve this?
Simply:
String input = "FIELD,KEY,0,AREA,2,3,4";
String key = input.split(",")[1]; //gets "KEY"
String keyValue = input.split(",")[2]; //gets "0"
As a homework, I'm leaving you the task to find the expression that gets "AREA".
You can use #indexOf and #split to do this as I guess your format of String is like this
FIELD,KEY,key1,key2,ke3...,AREA,area1,area2,area3...
String input = "FIELD,KEY,0,AREA,2,3,4";
int indexOfKEY=input.indexOf("KEY");
int indexOfAREA=input.indexOf("AREA");
String key[]=input.substring(indexOfKEY+4,indexOfAREA-1).split(",");
String area[]=input.substring(indexOfAREA+5).split(",");
How about something like that:
static Map<String,List<Integer>> parse(String input) {
Map<String,List<Integer>> result = new HashMap<String,List<Integer>>();
String[] items = input.split(",");
int i = 0;
while (i < items.length) {
String name = items[i++];
List<Integer> list = new ArrayList<Integer>();
while (i < items.length && items[i].matches("^[0-9]+$")) {
list.add(Integer.valueOf(items[i++]));
}
result.put(name,list);
}
return result;
}
public static void main(String[] args) {
Map<String,List<Integer>> map = parse("FIELD,KEY,0,AREA,2,3,4");
System.out.println(map.get("KEY"));
System.out.println(map.get("AREA"));
}

Categories