Java split string from array - java

I have a string array that contains some information.
Example:
String [] testStringArray;
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
This is exactly how the information is. Now my problem is I want to make each element a seperate element in an array and I want to split it based on the \n character.
So I want
newArray[0]=Jim,35
newArray[1]=Alex,45
newArray[2]=Mark,21
newArray[3]=Ana,18
etc etc. I am aware of the split method but won't this just split each array element into a completely new array instead of combining them?
If anyone could help, it would be appreciated. Thanks

Something like this:
// Splits the given array of Strings on the given regex and returns
// the result in a single array.
public static String[] splitContent(String regex, String... input) {
List<String> list = new ArrayList<>();
for (String str : input) {
for (String split : str.split(regex)) {
list.add(split);
}
}
return list.toArray(new String[list.size()]);
}
you can call it this way:
String[] testStringArray = ...;
String[] newArray = splitContent("\n", testStringArray);
Because of the use of varargs you can also call it like this:
String[] newArray = splitContent("\n", str1, str2, str3, str4);
where strX are String variables. You can use any amount you want. So either pass an array of Strings, or any amount of Strings you like.
If you don't need the old array anymore, you can also use it like this:
String[] yourArray = ...;
yourArray = splitContent("\n", yourArray);

String[] testStringArray = new String[2];
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21";
testStringArray[1]= "Jiam,35\nAleax,45\nMarak,21";
for(String s : testStringArray) {
String[] temp = s.split("\n");
for(String t : temp) {
result.add(t);
}
}
String[] res = result.toArray(new String[result.size()]);

Try This is working Code >>
String[] testStringArray = new String[2]; // size of array
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21"; // store value
testStringArray[1]= "Ana,18\nMegan,44";
for(String s : testStringArray) {
String[] temp = s.split("\n"); // split from \n
for(String t : temp) {
result.add(t); // add value in result
System.out.print(t);
}
}
result.toArray(new String[result.size()]);

you can first merge the strings into one string and then use the split method for the merged string.
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
StringBuffer sb = new StringBuffer();
for(String s : testStringArray){
s = s.trim();
sb.append(s);
if (!s.endWith("\n")){
sb.append("\n");
}
}
String[] array = sb.toString().split("\n");

Try this. It is simple and readable.
ArrayList<String> newArray = new ArrayList<String>();
for (String s : testStringArray) {
newArray.addAll(Arrays.asList(s.split("\\n"));
}

Firstly, you can't write what you just did. You made a String array, which can only contain Strings. Furthermore the String has to be in markers "" like "some text here".
Furthermore, there can only be ONE String at one place in the array like:
newArray[0] = "Jim";
newArray[1] = "Alex";
And NOT like:
newArray[0] = Jim;
And CERTAINLY NOT like:
// Here you're trying to put 2 things in 1 place in the array-index
newArray[0] = Jim, 35;
If you wan't to combine 2 things, like an name and age you have to use 2D array - or probably better in your case ArrayList.
Make a new class with following object:
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
And afterwards go to your class where you want to use the original array, and write:
ArrayList<Person> someNameOfTheArrayList = new ArrayList<Person>();
someNameOfTheArrayList.add(new Person("Jim", 32));
someNameOfTheArrayList.add(new Person("Alex", 22));

Related

Converting array list to a string array

I've been trying to convert my string array list to a string array so I can print it but have been unable to do so.
This is the class I have, randomQuestion which takes in an array list from the gameQuestions method in the same class.
I have never tried to convert an array list using a loop before hence the difficulty, I was able to convert it fine with the code
String[] questions = data1.toArray(new String[]{});
But I need it to loop through using a for loop to store it in an array which I can then print one at a time once a question is answered successfully.
The error I'm receiving from netbeans is cannot find symbol
Symbol:methodtoArray(String[]) for the .toArray portion below.
public String[] randomQuestion(ArrayList data1) {
Collections.shuffle(data1);
for (int question = 0; question < 10; question++) {
ranquestions = data1.get(question).toArray(new String[10]);
}
return ranquestions;
}
Any help would be greatly appreciated.
You can use List.toArray(). Class List has a method:
<T> T[] toArray(T[] a);
Assuming you have an ArrayList<String>, you can use String.join(delimiter, wordList) in order to concatenate all the elements to a single String:
public static void main(String[] args) {
// example list
List<String> words = new ArrayList<String>();
words.add("You");
words.add("can");
words.add("concatenate");
words.add("these");
words.add("Strings");
words.add("in");
words.add("one");
words.add("line");
// concatenate the elements delimited by a whitespace
String sentence = String.join(" ", words);
// print the result
System.out.println(sentence);
}
The result of this example is
You can concatenate these Strings in one line
So using your list, String.join(" ", data1) would create a String with the elements of data1 delimited by a whitespace.
The question is how to create an array with only 10 elements of the list, if I understood correctly.
Streams (Java 8):
String[] ranquestions = data1.stream()
.limit(10)
.toArray(String[]::new);
Loop (based on question, avoiding unnecessary changes):
String[] ranquestions = new String[10];
for(int question = 0; question < 10; question++) {
ranquestions[question] = data1.get(question);
}
always assuming List<String> data1, if not some conversion is needed.
Example:
String[] ranquestions = data1.stream()
.limit(10)
.map(String::valueOf)
.toArray(String[]::new);
or, loop case:
ranquestions[question] = String.valueOf(data1.get(question));
You can do:
private String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
If you are sure you are getting a list of string (question) you can instead
private String[] randomQuestions(List<String> data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
Edit 1
private static String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
String[] randomQuestions = new String[data.size()];
for(int i=0; i<data.size(); i++){
randomQuestions[i] = String.valueOf(data.get(i));
}
return randomQuestions;
}

Transform Set<Keyword> into String[]

I have an object Keyword that stores a String with the text of the keyword and a set o keywords (Set<Keyword>) that I need to transform into a String array. Is there a quick/easy way to do this or I need to iterate the set and add each keyword one by one?
EDIT:
For those asking for Keyword class:
#Entity
public class Keyword {
// ...
#Basic
private String value;
// ...
// Getters & Setters
}
Every class that implements Collection intefrace (and that includes Set) has toArray() method:
String[] array= set.toArray(new String[0]);
In case of a set that is parametrized with some other type, e.g. Set<Keyword> you would have to do something like:
Keyword[] array= set.toArray(new Keyword[0]);
String[] stringArray= new String[array.length];
for (int i=0; i<array.length; i++) {
stringArray[i]= array[i].getThatString();
}
Try this:
String[] arr = set.toArray(new String[set.size()]);
... is what I would have said, if you had a Set<Object>.
No, there is no way to directly convert a Set<Keyword> to a String[] since there is no direct relationship between Keyword and String. You will have to iterate over the set:
String[] arr = new String[set.size()];
int i = 0;
for (Keyword word : set)
arr[i++] = word.toString();
If you use Guava, you may use this:
Lists.transform(Lists.newArrayList(theSet), Functions.usingToString())
.toArray(new String[theSet.size()])
And this only scratches the surface of what Guava can actually do.
There is no specific way to do this . You can either convert Set to Object[] using set.toArray and then iterate over the array
or
iterate over the set directly
You may need to add toString() method to your Keyword class as shown below. Or you can use a separate transformer class/method.
class Keyword {
private String value;
Keyword(String v) {
this.value = v;
}
public String toString() {
return value;
}
}
.
I would say iterate the set and add each keyword one by one is your best possible strategy.
System.out.println(toStringArray(set));
.
private static String[] toStringArray(Collection<?> set) {
String[] arr = null;
if (set != null) {
arr = new String[set.size()];
int i = 0;
for (Object o : set) {
arr[i++] = o.toString();
}
}
return arr;
}
.
However if you really want, you can have a dirty workaround as shown below. Only issue here is that your keyword value cannot contain comma (,) as it is used by split() method.
String str = set.toString();
str = str.substring(1, str.length() - 1);
String[] asStringArray = str.split(",");
System.out.println(asStringArray);

Parse from List<String> Java

I am attempting to parse the value of the elements in a List declared as thus:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
The values are such as this:
a:1-2
b:3-5
but I want one ArrayList with the first number (i.e. 1, 3) and another with the second (i.e. 2, 5). I have this worked out... Sorta:
String delims= "\t"; String delim2= ":"; String delim3= "-";
String splits2[]; String splits3[]; String splits4[];
Map<String,String> dupMap = new TreeMap<String, String>();
List<String> uniqueList = new ArrayList<String>(dupMap.values());
ArrayList<String> parsed2 = new ArrayList<String>();
ArrayList<String> parsed3 = new ArrayList<String>();
ArrayList<String> parsed3two= new ArrayList<String>();
double uniques = uniqueList.size();
for(int a=0;a<uniques;a++){
//this doesn't work like it would for an ArrayList
splits2 = uniqueList.split(delim2) ;
parsed2.add(splits2[1]);
for(int q=0; q<splits2.length; q++){
String change2 = splits2[q];
if(change2.length()>2){
splits3 = change2.split(delim3);
parsed3.add(splits3[0]);
String change3=splits3[q];
if (change3.length()>2){
splits4 = change3.split(delims);
parsed3two.add(splits4[0]);
}
}
}
}
uniqueList.split does not work however and I don't know if there is a similar function for List. Is there any suggestions?
If you know that all of your data is in the form [something]:[num]-[num], you can use a regular expression like this:
Pattern p = Pattern.compile("^([^:]*):([^-]*)-([^-]*)$");
// I assume this holds all the values:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
for (String src : uniqueList) {
Matcher m = p.matcher(src);
if( m.find() && m.groupCount() >= 3) {
String firstValue = m.group(1); // value to left of :
String secondValue = m.group(2); // value between : and -
String thirdValue = m.group(3); // value after -
// assign to arraylists here
}
}
I didn't actually put the code in to add to the specific ArrayLists because I couldn't quite tell from your code which ArrayList was supposed to hold which value.
Edit
Per Code-Guru's comment, an implementation using String.split() would go something like this:
String pattern = "[:\\-]";
// I assume this holds all the values:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
for (String src : uniqueList) {
String[] parts = src.split(pattern);
if (parts.length == 3) {
String firstValue = parts[1]; // value to left of :
String secondValue = parts[2]; // value between : and -
String thirdValue = parts[3]; // value after -
// assign to arraylists here
}
}
Both approaches are pretty much the same in terms of efficiency.
From what I understand of your question, I would proceed as follows:
for each String in uniqueList
parse the string into a character and two integers (probably using a single call to [String.split()](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String, int))
insert the first integer into an List
insert the second integer into another List
This is in pseudocode. Translating into Java is left as an exercise to the reader.

Concating a String from an arraylist

I have an array list ArrayList<String> firstname; In this I am storing n number of names which have been parsed from an xml file.
Now from this ArrayList I need to take all the names and store it in a Single separate
String names along with a slash(/) between of each names.
For eg firstname= {a, c,f,g,h,j,k}
Now i want it to be as follows names= a/c/f/g/h/j/k
So far I have created a for loop to get values from the ArrayList by its size
String names;
for(int k=0;k<Appconstant.firstname.size();k++) {
names = Appconstant.firstname.get(k);
}
String names = TextUtils.join("/", Appconstant.firstname);
String names;
for(int k=0;k<Appconstant.firstname.size();k++)
{
if(k<=Appconstant.firstname.size()-1)
names += Appconstant.firstname.get(k)+"/";
else
names += Appconstant.firstname.get(k)
}
Though you should be using a StringBuilder instead.
Off the top of my head, but something like this:
StringBuilder builder = new StringBuilder();
for(String name : firstname)
{
builder.append(name).append('/');
}
// Remove last '/'
builder.deleteCharAt(builder.length()-1);
StringBuilder myStrBuilder = null;
for(String aName:yourNameList)
{
myStrBUilder.append(aName+"/");
}
myStrBuilder.deleteCharAt(myStrBUilder.length()-1)

Complex string split in Java

Consider the following String :
5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+
Here is how I want to split string, split it with + so I get this result :
myArray[0] = "5|12345|value1|value2|value3|value4";
myArray[1] = "5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4";
if string has doesn't contain char "?" split it with "|" and continue to part II, if string does contain "?" split it and for each part split it with "|" and continue to part II.
Here is part II :
myObject.setAttribute1(newString[0]);
...
myObject.setAttribute4(newString[3]);
Here what I've got so far :
private static String input = "5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+";
public void mapObject(String input){
String[] myArray = null;
if (input.contains("+")) {
myArray = input.split("+");
} else {
myArray = new String[1];
myArray[0] = input;
}
for (int i = 0; i < myArray.length; i++) {
String[] secondaryArray = null;
String[] myObjectAttribute = null;
if (myArray[i].contains("?")) {
secondaryArray = temporaryString.myArray[i].split("?");
for (String string : secondaryArray) {
myObjectAttribute = string.split("\\|");
}
} else {
myObjectAttribute = myArray[i].toString().split("\\|");
}
myObject.setAttribute1(myObjectAttribute[0]);
...
myObject.setAttribute4(myObjectAttribute[3]);
System.out.println(myObject.toString());
}
Problem :
When I split myArray, going trough for with myArray[0], everything set up nice as it should.
Then comes the myArray[1], its split into two parts then the second part overrides the value of the first(how do I know that?). I've overridden toString() method of myObject, when I finish I print the set values so I know that it overrides it, does anybody know how can I fix this?
I'm not quite sure what the intention is here, but in this snippet of code
secondaryArray = temporaryString.split("?");
for (String string : secondaryArray) {
myObjectAttribute = string.split("\\|");
}
if secondaryArray has two elements after the split operation, you are iterating over each half and re-assigning myObjectAttribute to the output of string.split("\|") each time. It doesn't matter what is in the first element of secondaryArray, as after this code runs myObjectAttribute is going to contain the result of split("\\|") on the last element in the array.
Also, there is no point in calling .toString() on a String object as you do in temporaryString = myArray[i].toString().
The code doesn't seem to be able to handle the possible expansion of strings in the secondary case. To make the code clearer, I would use a List rather than array.
private static String input = "5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+";
private void split(List<String> input, List<String> output, String split) {
for (String s: input) {
if (s.contains(split))
{
output.addAll(Arrays.asList(s.split(Pattern.quote(split)));
}
else
output.add(s);
}
}
public void mapObject(String input) {
List<String> inputSrings = new ArrayList<String>();
List<String> splitPlus = new ArrayList<String>();
inputStrings.add(input);
split(inputStrings, splitPlus);
List<String> splitQuest = new ArrayList<String>();
split(splitPlus, splitQuest, "?");
for (String s: splitQuest) {
// you can now set the attributes from the values in the list
// splitPipe
String[] attributes = s.split("\\|");
myObject.setAttribute1(attributes[0]);
....
myObject.setAttribute4(attributes[3]);
System.out.println(myObject);
}
}

Categories