Step 1: Split your given string input as Arrays.asList(city.split("::"));, you alresy did it.
Step 2: Split each list in to array like, example Tamilnadu;chennai-madurai-salem using String both[]=string.split(";"); here you will get seperated state and cities. like both[0] is State. both[1] is chennai-madurai-salem
Step 3: Split the cities string in both[1] usig both[1].split("-")
So Demo code I have given as below. You can modify.
public static void main(String[] args) {
String city = "Tamilnadu;chennai-madurai-salem::Kerala;cochin-tiruvandrum-calicut";
ArrayList<String> mState = new ArrayList<String>();
ArrayList<String> mCity = new ArrayList<String>();
List<String> bothList= Arrays.asList(city.split("::"));
for (String string : bothList) {
String both[]=string.split(";");
String state=both[0];
List<String> tempCityList=Arrays.asList(both[1].split("-"));
mState.add(state);
mCity.addAll(tempCityList);
}
System.out.println("Your states");
for (String string : mState) {
System.out.print(string+" ");
}
System.out.println("\nYour cities");
for (String string : mCity) {
System.out.print(string+" ");
}
}
Answer from mahesh on Stack OverflowStep 1: Split your given string input as Arrays.asList(city.split("::"));, you alresy did it.
Step 2: Split each list in to array like, example Tamilnadu;chennai-madurai-salem using String both[]=string.split(";"); here you will get seperated state and cities. like both[0] is State. both[1] is chennai-madurai-salem
Step 3: Split the cities string in both[1] usig both[1].split("-")
So Demo code I have given as below. You can modify.
public static void main(String[] args) {
String city = "Tamilnadu;chennai-madurai-salem::Kerala;cochin-tiruvandrum-calicut";
ArrayList<String> mState = new ArrayList<String>();
ArrayList<String> mCity = new ArrayList<String>();
List<String> bothList= Arrays.asList(city.split("::"));
for (String string : bothList) {
String both[]=string.split(";");
String state=both[0];
List<String> tempCityList=Arrays.asList(both[1].split("-"));
mState.add(state);
mCity.addAll(tempCityList);
}
System.out.println("Your states");
for (String string : mState) {
System.out.print(string+" ");
}
System.out.println("\nYour cities");
for (String string : mCity) {
System.out.print(string+" ");
}
}
Here is the example
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Prasad on 6/17/2014.
*/
public class stack {
public static void main(String[] args) {
String s="Tamilnadu;chennai-madurai-salem::Kerala;cochin-tiruvandrum-calicut";
ArrayList<String> x1=new ArrayList<String>();
ArrayList<String> x2=new ArrayList<String>();
String string[]=s.split("::");
for(String y:string){
try{
String[] temp=y.split(";");
x1.add(temp[0]);
x2.add(temp[1]);
}catch(Exception e){}
}
System.out.println(x1.toString());
System.out.println(x2.toString());
}
}
Convert comma separated String to List
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas.
Please note that this returns simply a wrapper on an array: you CANNOT for example .remove() from the resulting List. For an actual ArrayList you must further use new ArrayList<String>.
Arrays.asList returns a fixed-size List backed by the array. If you want a normal mutable java.util.ArrayList you need to do this:
List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));
Or, using Guava:
List<String> list = Lists.newArrayList(Splitter.on(" , ").split(string));
Using a Splitter gives you more flexibility in how you split the string and gives you the ability to, for example, skip empty strings in the results and trim results. It also has less weird behavior than String.split as well as not requiring you to split by regex (that's just one option).
Unless Splitter is doing any magic, the getTokenizeString method is obsolete here. You can perform the entire processing as a single operation:
Map<String,String> map = Pattern.compile("\\s*-\\s*")
.splitAsStream(responseString.trim())
.map(s -> s.split("~", 2))
.collect(Collectors.toMap(a -> a[0], a -> a.length>1? a[1]: ""));
By using the regular expression \s*-\s* as separator, you are considering white-space as part of the separator, hence implicitly trimming the entries. There’s only one initial trim operation before processing the entries, to ensure that there is no white-space before the first or after the last entry.
Then, simply split the entries in a map step before collecting into a Map.
First of all, you don't have to split the same String twice.
Second of all, check the length of the array to determine if a value is present for a given key.
HashMap<String, String> map=
list.stream()
.map(s -> s.split("~"))
.collect(Collectors.toMap(a -> a[0], a -> a.length > 1 ? a[1] : ""));
This is assuming you want to put the key with a null value if a key has no corresponding value.
Or you can skip the list variable :
HashMap<String, String> map1 =
MyClass.getTokenizeString(responseString, "-")
.stream()
.map(s -> s.split("~"))
.collect(Collectors.toMap(a -> a[0], a -> a.length > 1 ? a[1] : ""));
Have you tried running it through Split with the regex parameter as"[\\[\\]\\', ]"
Basically any of [,],,,', - more information here
This is my code , Hope it will help
String s1 = "['Aaaa', 'Eeee', 'Ffff', 'Cccc', 'Dddd']";
String s2 = "['Aaaa', 'Eeee']";
String[] xx = s1.substring(2, s1.length() - 2).split("', '");
If you inspect the output of System.out.println(Tuples); you'll notice a problem:
Tuples.add(List2) does not make a copy of List2. You're storing multiple references to the same List2 in Tuples, and appending more data to the same List2. So you end up with a very long list (i.e., List2) containing all tuples concatenated, and that list replicated many times inside Tuples.
Instead of
Tuples.add(List2);
try this instead:
Tuples.add(new ArrayList<>(List2));
List2.clear();
This will make elements of Tuples reference different lists.
I think you are doing it in a way too complicated way, just do:
List<String> inputList = new ArrayList<String>();
inputList.add("<b>SELL 512</b> lots of <b>[email protected]</b>");
inputList.add("<b>BUY 513</b> lots of <b>[email protected]</b>");
System.out.println("inputList: "+inputList);
List<List<String>> Tuples = new ArrayList<List<String>>();
List<String> list3 = new ArrayList<String>();
List<String> list4 = new ArrayList<String>();
List<String> list5 = new ArrayList<String>();
List<String> list6 = new ArrayList<String>();
for (int i = 0; i < inputList.size(); i++) {
String var = inputList.get(i).trim();
String[] splitArr=var.split("</b>|<b>|\\d*@"); //remove the \\d* if you expect to have xyz18 in output instead of x
list3.add((splitArr[1].split("\\s"))[0]);
list4.add((splitArr[1].split("\\s"))[1]);
list5.add(splitArr[3]);
list6.add(splitArr[4]);
Tuples.add(Arrays.asList(var.replaceAll("</b>|<b>", "")));
}
System.out.println("Tuples: "+Tuples);
System.out.println("list3: "+list3);
System.out.println("list4: "+list4);
System.out.println("list5: "+list5);
System.out.println("list6: "+list6);
OUTPUT:
inputList: [<b>SELL 512</b> lots of <b>[email protected]</b>, <b>BUY 513</b> lots of <b>[email protected]</b>]
Tuples: [[SELL 512 lots of [email protected]], [BUY 513 lots of [email protected]]]
list3: [SELL, BUY]
list4: [512, 513]
list5: [xyz, abc]
list6: [112.00, 113.00]
There are many encoding formats that could lead to this string. One of them is JSON. So instead of writing the splitting code yourself, you should use one of the many existing JSON parsers. Have a look at the awesome-java project at GitHub to find one.
Then, your code should become as simple as:
JSONArray sampleList = JSON.parseArray(sample);
I would say it depends on what the code is for.
If it's a write once quick solution for some small task your current code is fine as it is. The idea here is that if it no longer does what you want, you don't mind rewriting it entirely since it was a quick and (not so) dirty solution in the first place.
If instead you intend to use this as part of a bigger project that you plan on maintaining/improving you might want to look into JSON-parsing like Roland Illig suggests.
You didn't mention where the string originates from. If you're able to change that code as well you can also take a look at alternatives. For example JSON/XML serialisation/deserialisation of an entire class.
Note: This is not a full answer, but it should enable you to solve your problem.
In your print statement System.out.println(result.add(String.valueOf(lines))); you print the return value of the add method instead of the string value you parsed.
Try to print result instead.
The problem here is that you are printing out the result of the function call result.add(). You will need to call result.add() on different line and call only String.valueOf(lines) or result.get(//index of last add) in the call to system.out. You can also loop through result afterward to get the same result.