How to remove the brackets [ ] from ArrayList#toString()? - java

I have created an Array List in Java that looks something like this:
public static ArrayList<Integer> error = new ArrayList<>();
for (int x= 1; x<10; x++)
{
errors.add(x);
}
When I print errors I get it errors as
[1,2,3,4,5,6,7,8,9]
Now I want to remove the brackets([ ]) from this array list. I thought I could use the method errors.remove("["), but then I discovered that it is just boolean and displays a true or false. Could somebody suggest how can I achieve this?
Thank you in advance for your help.

You are probably calling System.out.println to print the list. The JavaDoc says:
This method calls at first String.valueOf(x) to get the printed object's string value
The brackets are added by the toString implementation of ArrayList. To remove them, you have to first get the String:
String errorDisplay = errors.toString();
and then strip the brackets, something like this:
errorDisplay = errorDisplay.substring(1, errorDisplay.length() - 1);
It is not good practice to depend on a toString() implementation. toString() is intended only to generate a human readable representation for logging or debugging purposes. So it is better to build the String yourself whilst iterating:
List<Integer> errors = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int x = 1; x<10; x++) {
errors.add(x);
sb.append(x).append(",");
}
sb.setLength(sb.length() - 1);
String errorDisplay = sb.toString();
Note that this is not an array, just a String displaying the contents of the list. To create an array from a list you can use list.toArray():
// create a new array with the same size as the list
Integer[] errorsArray = new Integer[errors.size()];
// fill the array
errors.toArray(errorsArray );
EDIT: From an object-oriented perspective one could argue that errors and errorsDisplay conceptually belong together in a class, e.g:
public class Errors {
private final List<Integer> codes = new ArrayList<>();
public void add(int error) {
codes.add(error);
}
public Stream<Integer> get() {
return codes.stream();
}
#Override
public String toString() {
return codes.stream()
.map(Object::toString)
.collect(Collectors.joining(", "));
}
}

Short answer: System.out.println(errors.toString().substring(1, errors.toString().length() - 1))
Explanation: when you call System.out.println(obj) with an Object as a parameter, the printed text will be the result of obj.toString(). ArrayList.toString() is implemented in a way that makes it represent its content between brackets [] in a comma separated concatenation of each of the contained items (their .toString() representation as well).
It is not a good practice to rely on another class's toString() implementation. You should use your own way to format your result.

The brackets you see are just an automatic way to display a List in JAVA (when using System.out.println(list); for example.
If you do not want them to show when showing it, you can create a custom method :
public void showList(List<Integer> listInt)
{
for(int el : listInt)
{
System.out.print(el + ", ");
}
}
Then adjust this code to show this according to your liking !

The brackets are not actually within the list it's just a representation of the list. If any object goes into a String output the objects toString() method gets called. In case of ArrayList this method delivers the content of the list wrapped by this brackets.
If you want to print your ArrayList without brackets just iterate over it and print it.

There are not brackets inside your list.
This is just the way Java prints a list by default.
If you want to print the content of your list, you can something like this
for (Integer error : errors) {
System.out.format("%d ", error);
}

If you print your error list, it will internally call the toString() method of your list and this method add the brackets. There are a few possibilities. You can get the String via toString() method an remove the brackets from the String. Or you write your own method to print the List.
public static <T> void printList(List<T> list)
{
StringBuilder output = new StringBuilder();
for(T element : list)
output.append(element + ", ");
System.out.println(output);
}

String text = errors.toString().replace("[", "").replace("]", "");//remove brackets([) convert it to string

brackets is not a part of your array list, since as you've mentioned it's Integer typed
ArrayList<Integer>
when you print errors using
System.out.println(errors);
it's just formatting your data, just iterate over the array and print each value separately

System.out.println(error.toString().substring(1, error.toString().length()-1));
This worked for me

For that, you can use String.join method like below.
String.join(",",errors);

This is an ArrayList of Integer. This ArrayList can not contain a character like '['. But you can remove an Integer from it like this -
error.remove(3);

You can write like this.
String output = errors.toString().replaceAll("(^\\[|\\]$)", "");

You can simply remove all the brackets using replaceAll() method like this:-
System.out.println(errors.toString().replaceAll("[\\[\\]]", ""));

I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.
Please refer to my Code & Output below:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList mylist = new ArrayList();
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
System.out.println("Enter Value " + i + " to add: ");
mylist.add(scan.nextLine());
}
System.out.println("=======================");
for(int j = 0; j < 5; j++) {
System.out.print(mylist.get(j));
}
}
}
OUTPUT
Enter Value 0 to add:
1
Enter Value 1 to add:
2
Enter Value 2 to add:
3
Enter Value 3 to add:
4
Enter Value 4 to add:
5
=======================
12345

Related

Fail to randomize java string array

I want to randomize or shuffle the order of the string array using the code below
public static void main(String[] args) {
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[]=str;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=0; i<str.length; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<str.length; i++) {
strTmp[i]=str[list.get(i)];
System.out.println(strTmp[i]);
}
}
The reason I do it like this instead of print it out directly is because I want to make it into a function later on. That's why I passed it to strTmp[] as that is what I want the function to return. But, the code just didn't function as I expected. It prints out several same value. How can I do it the right way? Thanks for the answer...
You almost had it, but you are referencing the same array twice and swap the contents of it. Change this line
String strTmp[] = str;
to
String strTmp[] = new String[str.length];
If you don't want to change the array str. Try this.
String str[] = {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[] = str.clone();
Collections.shuffle(Arrays.asList(strTmp));
System.out.println(Arrays.toString(strTmp));
output
[Xcgi, Cvda, Atdr, Mbeds, 0bda, Vxds]
When you do String strTmp[]=str;, both str and strTmp are references to the same array. So when putting elements in, you are overwriting old elements including those have not yet been moved.
You may just do
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
Collections.shuffle(Arrays.asList(str));
This works because Arrays.asList() does not create a new list, it merely provides a list view on the array. Any changes to the list change the array. Including shuffling it. Edit: This works for an array of strings and an array of any other reference type. As WJS points out, this will not work for an array of primitives (e.g., int[]) since Arrays.asList(arrayOfPrimitives) will create a list view of a newly created array of one elemeent, the primitive array.
If you require a new array with the shuffled strings and the old array unmodified, the solution is:
List<String> list = new ArrayList<>(Arrays.asList(str));
Collections.shuffle(list);
String[] newStr = list.toArray(new String[0]);
System.out.println("Original array: " + Arrays.toString(str));
System.out.println("New shuffled array: " + Arrays.toString(newStr));
Edit: Output from one example run:
Original array: [Vxds, Cvda, Xcgi, Atdr, Mbeds, 0bda]
New shuffled array: [0bda, Cvda, Mbeds, Vxds, Xcgi, Atdr]
As you can see, the original array is unmodified.
Edit: Since Java 11 it’s nicer to create the new array using Collection.toArray(IntFunction<String[]>):
String[] newStr = list.toArray(String[]::new);
See both code snippets run live in IdeOne.
I understand that you want to randomized your array in every execute. Here is the code for this.
import java.util.*;
public static void main(String[] args) {
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
List<String> list =Arrays.asList(str);
Collections.shuffle(list);
System.out.println(list);
}

Java: Comparing ArrayList item to User Input String

I have seen other threads on this, but I still don't understand the best approach. Issue is as started: One can't compare user input that is a String to an arrayList item (object). My List will be over 40 items.
So when I try to compare classesList.get(0) to the user input mage. It won't work.
List<String> classesList = new ArrayList<String>();
classesList.add("mage");
classesList.add("warrior");
classesList.add("thief");
Scanner input = new Scanner(System.in);
String input = input.next();
for (int counter = 0; counter < classesList.size(); counter++) {
if (input == classesList.get(counter)) {
//won't run body since can't compare
}
}
I found some who converted the arrayList to be a String. But I am unsure how I could then easily search through my list. I'd much rather leave it as a List instead. Is the best method to this approach?
String[] classesArray = classesList.toArray(new String[classesList.size()]);
I think you have to see if input string exist in the ArrayList, you have to use contains() method.
if(classesList.contains(input)) {
//Found in the arraylist.
}
But with you method, you can't compare strings using == operator. You should use equals() method for comparision
List<String> classesList = new ArrayList<String>();
classesList.add("mage");
classesList.add("warrior");
classesList.add("thief");
Scanner input = new Scanner(System.in);
String input = input.next();
boolean isExist = false;
for (String item : classesList) {
if (input.equals(classesList.get(counter))) {
//Your logic if it's there.
isExist = true;
break;
}
}
if(isExist) {
//Found in the arraylist.
}
Also if you want to make this comparision with ingnoring the case, you shoudl consider using equlasIgnoreCase() method instead of equals() method.
I don't fully understand your question, however you can test if a given String exists in the list using contains()
Some other pointers
Never compare Strings with ==, use .equals(). See this question
Iteration can be done more simply using (String element : list) syntax
Yes what you read is right, not to use following:
for (int counter = 0; counter < classesList.size(); counter++) {
if (input == classesList.get(counter)) {
//won't run body since can't compare
}
}
You cannot use == for comparison instead you should use equals method if you are using loop:
for (int counter = 0; counter < classesList.size(); counter++) {
if (input.equals(classesList.get(counter))) {
//won't run body since can't compare
}
}
Otherwise easier way is to use contains as mentioned in other answer.
Also see How do I compare strings in Java?
Cheers !!
You can use the contains method on your list to see if a particular string is contained inside of it, instead of iterating across it. However, the underlying list will still be iterating over the contents of the list internally.
What you could do instead, to improve speed, is to use a Set instead, which has a nice property of having contains be run in constant time.
Set<String> classesSet = new HashSet<>();
// none of your other code has to change, except for:
if(classesSet.contains(input)) {
// logic
}

Iterating over split string

After looking for a while, it's still bugging me:
I have a simple code where I want to retrieve data looking like:
data1/data2/style…
and I want to separate the data at each /. So I have written:
MyData = data.split("/")
and then:
for (i = 0; i < myData.size; i++)
to iterate over the values. But I'm getting the following error:
no signature of method length for type argument: () values: []
so I'm assuming that myData is empty.
if you want to iterate using an integer, you should use MyData.size() in the for loop.
But it is a better idea to do:
String[] myData = data.split("/");
for (String s: myData) {
System.out.println(s);
}
to use each string of the array.
If the iteration only iterates once over your array, then it may be your string that has a problem. As a double check, you may do:
System.out.println(myData.size());
You may also want to add a breakpoint after the .split() and look using a debugger if the array really contains all the strings you're expecting it to contain.
I am having some trouble understanding your question, even with the translation :)
In the line
mesDonnees = maDonnee.split("/");
mesDonnees needs to be a String array (String[]) and you can loop through it like:
for (String str : mesDonnees) {
//... do somwething with str
}
You can rename str something in French if you like, I couldn't think of a suitable name

Java LinkedList obtaining first element

I have an Java LinkedList which stores two values (code below).
I was wondering how i can obtain the first value only?
I have:
LinkedList list = new LinkedList();
list.add(number+" "+string);
I want to be able to just print out number from the list. Is it possible?
First of all, note that by doing list.add(number + " " + string) you're adding a single object, namely the string formed by concatenating number and string.
That said, you could try something like this, to get the first part of the first element:
list.get(0).split(" ")[0]
Example:
int number = 17;
String string = "hello";
LinkedList<String> list = new LinkedList<String>();
list.add(number+" "+string);
// Print number of first item:
System.out.println(list.get(0).split(" ")[0]); // prints "17"
I think you mean the number only.
First get the object at index 0:
String node = list.get(0);
Then extract the first part by looking for the space
String num = node.substring(0,node.indexOf(' '));
Although I suggest looking into HashMaps for such implementation, which takes Key,Value pairs:
For your example, you will need something like:
Map<Long,String> myMap = new HashMap<Long,String>();
myMap.put(number,string);
I'd suggest encapsulating your number and string into a class, like this.
public final class Pojo {
private final Number number;
private final String string;
public Pojo(Number number, String string) {
this.string = string;
this.number = number;
}
public void getNumber() {
return number;
}
public void getString() {
return string;
}
#Override
public String toString() {
return number + " " + string;
}
}
Then, create your List like this:
List<Pojo> list = new LinkedList<Pojo>(); // use generics for compile-time type safety
list.add(new Pojo(42, "Answer to the Ultimate Question of Life, the Universe, and Everything"); // add a Pojo
System.out.println(list.get(0).getNumber());
The List does not store two values. It stores one Object, the String created by concatenating number with a space and the String.
If you want to access individual Objects, you should either use a Map instead of a List or create a custom Object that holds number and string:
a)
Map<Integer, String> map = new Hashmap<Integer, String>();
map.put(number, string);
b)
public class MyObject{
private Number number;
private String string;
// + getters and setters
}
Also:
a) you should not use Non-generic Collections anymore. Generics were introduced 7 years ago, there should not be any reason not to use them these days.
So you should use this:
LinkedList<String> list = new LinkedList<String>();
Or this:
LinkedList<MyCustomObject> list = new LinkedList<MyCustomObject>();
b) are you sure you want a LinkedList? In most cases, ArrayList is the general purpose List implementation. LinkedList performs better if you have many add() statements and don't know in advance how large your List will be, but ArrayList performs a lot better for random access.
You are adding a string to that list. x + y, where either x or y is a string produces a string. If you want to have access to the number and the string, you should consider using another type - not a String here. Something like:
LinkedList<Pair<Number, String>> list = new LinkedList<Pair<Number, String>();
list.add(new Pair<Number, String>(number, string));
This way, to obtain the number, stored in the first element of the list:
Pair thePair = list.get(0);
number = (Number)thePair.left;
Pair is a class, you can find in Apache Commons:
http://commons.apache.org/lang/api-3.0-beta/org/apache/commons/lang3/Pair.html
(A source for many useful Java classes)
number+" "+string
Acts as a single string, if you want to get the number:
list.get(index).split(" ")[0]
Even if it works, this is not a clear way to manage a pair of values.
From an object-oriented point of view (and this is the right context :D ), use directly an object:
class Pair {
int number;
String str;
}
Put your object to the list:
Pair pair = new Pair();
pair.number = 1;
pair.str = "hello";
list.add(pair);
And get your number:
((Pair)list.get(0)).number;
Of course you can use class methods and generics to manage all in a better way.
when you are initiating a Linkedlist in java, you should specify the data type that you are going to store in. You haven't done so. As your requirement it should be:
LinkedList<int> list=new LinkedList<>();
After that you can add your elements:
list.add(<number>);
Then you can get the first element:
list.getFirst();
Then you can print that.

For-Each and Pointers in Java [duplicate]

This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 5 years ago.
Ok, so I'm tyring to iterate through an ArrayList and remove a specefic element. However, I am having some trouble using the For-Each like structure. When I run the following code:
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for(String t : arr)
{
t = " some other value "; //hoping this would change the actual array
}
for(String t : arr)
{
System.out.println(t); //however, I still get the same array here
}
My question in, how can I make 't' a pointer to 'arr' so that I am able to change the values in a for-each loop? I know I could loop through the ArrayList using a different structure, but this one looks so clean and readable, it would just be nice to be able to make 't' a pointer.
All comments are appreciated! Even if you say I should just suck it up and use a different construct.
I think the best approach may be to use a for loop.
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i < arr.size(); i++) {
String t = arr.get(i);
if (// your condition is met) {
arr.set(i, "your new value");
}
}
The problem is that you're trying to change the loop-scoped reference t to let it point to a new String instance. This ain't going to work. It does not refer the actual entry in the arraylist. You need to change the actual value of the reference. If String was mutable and provided a fictive set() method for that, you could in theory do
for (String t : arr) {
t.set("some other value");
}
or so, but that's not possible as it is immutable. Better get a handle of the entrypoint in the array itself using the normal for loop:
for (int i = 0; i < arr.size(); i++) {
arr.set(i, "some other value");
}
If you insist in using the enhanced for loop, then you need to replace String by StringBuilder, which is mutable:
for (StringBuilder t : arr) {
t.delete(0, t.length()).append("some other value");
}
Remember, Java is pass-by-value, not pass-by-reference.
For-each doesn't give you an index pointer, so you just can't use it to change an immutable value.
Either use a for-loop with an index or use a mutable type (like StringBuffer, not String)
An array of objects (like strings) in Java is a contiguous block containing an ordered series of references. So, when you have an array of 4 strings, what you really have is 4 references stored IN the array, and 4 string objects that are outside of the array but are referenced by its 4 elements.
What the for-each construct in Java does is create a local variable and, for each iteration, copy into that local variable the reference from the array cell that corresponds to that iteration. When you set the loop variable (t = " some other value") you are putting a reference to a new string, "some other value", into the local variable t, not into the array.
The contrasts with some other languages (like Perl) where the loop variable acts like an alias to the array/list element itself.
Your code is re-written by the compiler as something like this:
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for (final Iterator <String> i = arr.iterator(); i.hasNext();) {
String t;
t = i.next();
t = " some other value "; // just changes where t is pointing
}
To do what you want you would have to write the for loop like this:
for (final ListIterator<String> i = arr.iterator(); i.hasNext();) {
final String t;
t = i.next();
i.set("some other value");
}
Iterator does not have the set method, only ListIterator does.
Basically you want to remove the String t from the list arr. Just do a arr.remove(t) and you could be done. But you can't do it while iterating over the same list. You'll get an Exception if you try to modify the list this way.
You have two options:
clone your list, iterate through the clone and remove the 'specific' String from the original list
create a list for delete candidates, add all 'specific' Strings to that list and, after iterating through the original list, iterate through the wastebin and remove everything you've collected here from the original list.
Option 1 is the easist, the clone can be made like:
List<String> clone = new ArrayList<String>(arr);
You seem to misunderstand how objects/references work in Java, which is pretty fundamental to using the language effectively. However, this code here should do what you want (apologies for the lack of explanation):
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for(int i = 0; i < arr.size(); i++)
{
arr.set(i, " some other value "); // change the contents of the array
}
for(String t : arr)
{
System.out.println(t);
}
I believe, this is not related to immutable or mutable.
t = " some other value "; //hoping this would change the actual array
t does not hold the reference to actual object. Java copies the value from arraylist and puts that value into t so array list value does not get affect.
HTH
This has been answered well. Still here is my suggestion. The var t inside loop is only visible there. It will not be seen outside the loop. You could do t.set() if it was not String.
Use a StringBuffer rather than plain strings. This way the string within is mutable.
Strings are immutable. If you had a mutable type like StringBuilder/Buffer, you could change the string in your iteration. You do have references, remember.

Categories

Resources