Properly formatting output of arraylist data? - java

I have a method in my switch statement explaining to print my arraylist
(i.e - System.out.println(drinkList);)
ArrayList<String> drinkList = new ArrayList<String>();
System.out.print("Please enter a drink information to add:\n");
inputInfo = scan.nextLine().trim();
drinkLink = DrinkParser.parseStringToDrink(inputInfo);
drinkList.add(drinkLink.toString()); //Take in user data to parse into parts
Then I called it using the code
System.out.println(drinkList);
My problem is the output prints the following as such:
[
Data Entry 1
,
Data Entry 2
]
I want to remove the brackets and the comma.

Don't call the toString() method on the ArrayList but loop through it and build a string yourself. Do something like:
StringBuilder builder = new StringBuilder();
for (String value : drinkList) {
builder.append(value) + ",";
}
String text = builder.toString();
System.out.println(text);
That'll make sure that the resulting string has the format that you want - in this case comma-separated entries.

Use the following code to remove the brackets and the commas:
String s = "[\nData Entry 1\n,\n Data Entry 2\n]";
String result = s.replaceAll("[^\\dA-Za-z\n]", "");
System.out.println(result);
The result is:
Data Entry 1
Data Entry 2
Or, you can override toString() method for your class.

Related

How to add new text to string without removing old string text?

Suppose I have a string String text = ""; and I add a text to it
text = "Apple";
now I want it not to remove the old String when I add a new one, like this
text = "Banana";
text = "Orange";
The output should be Apple, Banana, Orange, but the output i'm getting is Orange. How to do that in java?
Since String is Immutable then you can't edit t without reassigning it, however there is something called StringBuilder it is mutable so it can be changed.
String original=new String("blabla")
StringBuilder builder=new StringBuilder(myString);
original will not be affected expect if did you re assign it, but because of String builder is mutable you can do something like the following
builder.appened("someData");
and it should be retrieved as string like this
String newString=builder.toString()
You want the variable to hold multiple Strings. Yet, you don't want to append the String. A data structure is what you are looking for.
In this case, ArrayList can fulfill your needs:
ArrayList<String> texts = new ArrayList<String>();
texts.add("Apple");
texts.add("Banana");
texts.add("Orange");
You can get the elemebt by the order you added the Strings with index beggining with 0:
Systen.out.println(texts.get(0)); // prints "Apple"
To print all the elements from the ArrayList:
System.out.println(texts); // prints "Apple, Banana, Orange"
There are 2 ways you can achieve your desired output/result:
1. Using String:
You can simply append the new values at the end of String as following...
String text = "";
text = "Apple";
text = text + ", "+ "Banana";
text = text + ", "+ "Orange";
System.out.println(text); //output will be: Apple, Banana, Orange
2. Using StringBuilder: [recommended]
You can initialize StringBuilder, and use append() function to append new values at the end of the String and at last, you can get String from StringBuilder using toString() method of StringBuilder.
StringBuilder builder = new StringBuilder("");
builder.append("Apple").append(", ").append("Banana").append(", ").append("Orange");
String text = builder.toString();
System.output.println(text); //output will be Apple, Banana, Orange
2nd approach is recommended because when you append a String in StringBuilder, it does not create new object of String in String pool every time, it updates the existing object of StringBuilder.
Whereas String class in Java is immutable, so when you append a String in String literal, then it does update the existing object, it does create new object of String in String pool and points the reference to newly created String pool object.

How to concat string values in array list

I need to print all arraylist values at a time using concat.
Here is my code:
ArrayList<String> lst = new ArrayList<String>();
lst.add("hi");
lst.add("hello");
Iterator<String> itr = lst.iterator();
String result = null;
while(itr.hasNext()) {
Object element = itr.next();
result = element + " ";
}
System.out.println(result);
The expected result should be hi hello.
The current output however is hello (there is also a whitespace at the end).
Please prefer the List interface to the ArrayList concrete type. Assuming you are using Java 8+, you might use a Stream and Collectors.joining (and Arrays.asList) like
List<String> lst = Arrays.asList("hi", "hello");
String r = lst.stream().collect(Collectors.joining(" "));
System.out.println(r);
Which outputs
hi hello
As requested.
The error in your code is pretty small. In each iteration you assign a value to the result variable. However instead of updating your existing content you just erase it and enter a new value.
You do result = element + " ". But it should be something like result = result + element + " " or the same in short:
result += element + " ";
This way the first iteration will save hi in it and after that hello gets appended resulting in hi hello (instead of overriding the content of the first iteration).
Note that it now also has the whitespace at the end. You could delete it with result = result.substring(0, result.length() - 1). Or not add it in the last iteration, but then you need to count the iterations.
Please note that Java has a class StringJoiner that does exactly what you want, joining some elements together and also using a delimiter like whitespace. You use it like this:
StringJoiner sj = new StringJoiner(" ");
while(itr.hasNext()) {
Object element = itr.next();
sj.add(element);
}
String result = sj.toString();
Also note that since Java 8 there is an even shorter version of it:
String result = String.join(" ", list);

Storing multiple values in Java without using arrays

Take user input for 5 times, store them in a variable and display all 5 values in last. How can I do this in Java? Without using arrays, collections or database. Only single variable like String and int.
Output should look like this
https://drive.google.com/file/d/0B1OL94dWwAF4cDVyWG91SVZjRk0/view?pli=1
This seems like a needless exercise in futility, but I digress...
If you want to store them in a single string, you can do it like so:
Scanner in = new Scanner(System.in);
String storageString = "";
while(in.hasNext()){
storageString += in.next() + ";";
}
if you then input foo bar baz storageString will contain foo;bar;baz;. (in.next() will read the input strings to the spaces, and in.hasNext() returns false at the end of the line)
As more strings are input, they are appended to the storageString variable. To retrieve the strings, you can use String.split(String regex). Using this is done like so:
String[] strings = storageString.split(";");
the strings array which is retrieved here from the storageString variable above should have the value ["foo", "bar", "baz"].
I hope this helps. Using a string as storage is not optimal because JVM creates a new object every time a string is appended onto it. To get around this, use StringBuilder.
*EDIT: I originally had said the value of the strings array would be ["foo", "bar", "baz", ""]. This is wrong. The javadoc states 'Trailing empty strings are therefore not included in the resulting array'.
public static void main(String[] args) {
String s = "";
Scanner in = new Scanner(System.in);
for(int i=0;i<5;i++){
s += in.nextLine();
}
System.out.println(s);
}
Why dont you use Stingbuilder or StringBuffer, keep appending the some delimiter followed by the input text.
Use simple String object and concatenate it with new value provided by user.
String myString = "";
// while reading from input
myString += providedValue;

To string with adding bracket [duplicate]

This question already has answers here:
Print out elements from an Array with a Comma between the elements
(14 answers)
Closed 8 years ago.
Trying to delete the last comma and instead add an end bracket. How to go about this?
My code:
#Override
public String toString(){
String str="[";
for(double d:data) str+=d+", ";
return str;
}
Example data:
stat1 data = [
stat1 data = [50.0, 60.0,
stat1 data = [70.0, 80.0,
stat1 data = [90.0, 100.0,
stat1 data = [100.0, 110.0,
stat1 data = [
Sometimes it's hard to tell, ahead of time, when an element you're looking at in an iterator is the last one. In cases like this, it often works best to append the comma before each element instead of after, except for the first element. Thus:
String str = "[";
boolean first = true;
for (double d : data) {
if (!first) {
str += ", ";
}
str += d;
first = false;
}
str += "]";
Another possibility is to use the logic you have now but use substring or replace or some other method to remove the extra two characters, like
str = str.replaceFirst(", $", "]");
which uses a regular expression to replace ", " that appears at the end of the string with a right bracket.
It's better to just print the data in the toString method and add the typographical elements like '[' or comma separately accompanied with an if statement.
However if you insist to stick just to the toString method, add a boolean field to the class and set it to true if something is the last object and inside the toString method, check that field and do the right decision.

Appending text from array list to a String takes a lot of time

I am reading a Simple Notepad Text file containing a lot of data actually in a 3mb of size so you can imagine the number of words it can have! The problem is I am reading this file into a string then splits the string so that I can hold each single word inside an ArrayList(String). It works fine for me but the actual problem is that I am processing this array list for some purpose and then again I have to append or you can say put all the words of array list back to the String!
so that the steps are:
I read a text file into a String (alltext)
Split all words into an arraylist
process that array list (suppose I removed all the stop words like is, am, are)
after processing on array list I want to put all the words of array list back to the string (alltext)
then I have to work with that string (alltext)
(alltext is the string that must contains the text after all processing)
The problem is that at step number 4 it takes a lot of time to append all the words back to the string my code is:
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
alltext += line.trim().replaceAll("\\s+", " ") + " ";
}
br.close();
//Adding All elements from all text to temp list
ArrayList<String> tempList = new ArrayList<String>();
String[] array = alltext.split(" ");
for (String a : array) {
tempList.add(a);
}
//remove stop words here from the temp list
//Adding File Words from List in One String
alltext = "";
for (String removed1 : tempList) {
System.out.println("appending the text");
alltext += removed1.toLowerCase() + " ";
//here it is taking a lot of time suppose 5-10 minutes for a simple text file of even 1.4mb
}
So I just want any idea so that I can reduce the time for an efficient processing and relax the machine! I will be thankful for any suggestions and ideas...
Thanks
Use a StringBuffer instead of a String.
A String is immutable and thus you create a new Object everytime you append, which takes more and more time the longer your String becomes. A StringBuffer is mutable and made for cases like yours.
I would recommend StringBuilder
According to this stringbuilder-and-stringbuffer-in-java it's faster than a StringBuffer also check if you need the ArrayList because you can iterate through the array too

Categories