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
Related
I have a Collection of strings.
I need to replace some characters with given relevant characters.
I was tried this. But my code but doesn't work correctly.
public class MyPattern {
public static void main(String[] args)
{
String items;
Collection<String> arr = new ArrayList<String>();
arr.add("I00.30"); //Expected output: 100.30
arr.add("8B4.99"); //Expected output: 884.99
arr.add("B37.2B"); //Expected output: 837.28
arr.add("292.b4"); //Expected output: 262.64
arr.add("24|.7O"); //Expected output: 241.70
arr.add("B55.I4"); //Expected output: 855.14
arr.add("444.07"); //Expected output: 444.07
for(String item:arr)
{
System.out.println(item);
items = item.toUpperCase().replaceAll("l", "1")
.replaceAll("l", "1")
.replaceAll("i", "1")
.replaceAll("|", "1")
.replaceAll("G", "6")
.replaceAll("b", "6")
.replaceAll("B", "8")
.replaceAll("O", "0");
System.out.println(items);
}
}
}
The letters passed in the replaceAll() method has to be replaced in every item in the collection.
Is there any way to find the irrelevant character and replace it with the number (as shown in the code above) ?
Your code is resigning the variable item, it will not affect the list contents.
To be able to do that, you might change the type of variable arr to List. With that, you can iterate over it by using the traditional (index based) for loop.
List<String> arr = // initializing the list
for (int i = 0; i < arr.size(); i++) {
String item = replace(arr.get(i)); // method replace provided below
arr.set(i, item);
}
Another option is to use Java 8 replaceAll() method, which expects a function that will be applied to every element in the collection.
arr.replaceAll(str -> replace(str));
public static String replace(String source) {
return source.toUpperCase()
.replaceAll("[LI|]", "1")
.replaceAll("[GB]", "6")
.replace("O", "0");
}
Note that method replaceAll() that expect a regular expression is more expensive than replace(). Hence, when you don't need a regex, its better to use any flavor of replace() (with either char or String arguments).
Here you can benefit from replaceAll() by processing characters L, L and | in one go with a regular expression "[LI|]".
For more information on regular expressions take a look at this tutorial
There's also a minor issue in your code:
After toUpperCase() has been applied, it doesn't make sense to try to replace lowercase letters like 'l' or 'i'.
There's a clash "b", "6" and "B", "8".
I hope with all these hints you'll be able to manage to get it working.
Instead of using the for loop. You can use, stream.
For example, if you want to change i to 1 in every element, you can get it using the following code. And you want to
Collection<String> arr_new = arr.stream().map(String::toLowerCase).map(t->t.replaceAll("i",1)).map(String::toUpperCase);
Here, the first map converts the String to lower-case, the second map do replace what you need and the third map convert it to the upper case.
I hope this is what you are looking for.
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
I have a string places="city,city,town". I need to get "city,town". Basically get rid of duplicate entries in the comma separated string.
places.split(","); will give me array of String. I wonder, if I can pass this array to a HashSet or something, which will automatically get rid of duplicates, but trying something like:
HashSet test=new HashSet(a.split(","));
gives the error:
cannot find symbol
symbol : constructor HashSet(java.lang.String[])
Any neat way of achieving this, preferably with least amount of code?
HashSet<String> test=new HashSet<String>(Arrays.asList(s.split(",")));
this is because HashSet does not have a constructor that expects an array. It expects a collection, which is what I am doing here by Arrays.asList(s.split(","))
String s[] = places.split(",");
HashSet<String> hs = new HashSet<String>();
for(String place:s)
hs.add(place);
If you care about the ordering I'd suggest you use a LinkedHashSet.
LinkedHashSet test = new LinkedHashSet(Arrays.asList(a.split(",")));
Another way of doing this in Java 8 would be:
Lets say you have a string str which is having some comma separated values in it. You can convert it into stream and remove duplicates and join back into comma separated values as given below:
String str = "1,2,4,5,3,7,5,3,3,8";
str = String.join(",",Arrays.asList(str.split(",")).stream().distinct().collect(Collectors.toList()));
This will give you a String str without any duplicate
String[] functions= commaSeperatedString.split(",");
List<String> uniqueFunctions = new ArrayList<>();
for (String function : functions) {
if ( !uniqueFunctions.contains(function.trim())) {
uniqueFunctions.add(function.trim());
}
}
return String.join(",",uniqueFunctions);
or you can use linkedHashset
LinkedHashSet result = new LinkedHashSet(Arrays.asList(functions.split(",")));
I have list of array of strings, List <String []>, what is the best optimal approach to get contents of this list of array of strings?
public List<String []> readFromString (String data){
StringReader stringReader = new StringReader(data);
CVSReader reader = new CVSReader(stringReader);
return reader.readAll()
}
In above example, I want to see the actual contain of reader.readAll(), any suggestions as to what is the optimal way to get that information out?
I don't think there's any avoiding looping through the entire structure. Even if you call .toString(), which may well give what you want, you're still going to incur the cost of looping over the entire data structure:
String results = readFromString(data);
StringBuilder output = new StringBuilder();
for(String[] sArray : results) {
for(String s : sArray) {
output.append(s);
}
}
System.out.println(output);
(Note: insert formatting characters as required - you might want to put a comma after each string, and a \n after each list completes, to make the output more readable.)
By wanting to see the content and "get information out", if you mean that you want to send it to standard out, or your log file, to see a full dump of the data, you can use the List toString (i.e. System.out.println(reader.readAll()); ). It prints all values. The following unit test confirms it:
public void testListOfArraysToStringPrintsAllValues(){
String[] array1 = ["array1.1", "array1.2"];
String[] array2 = ["array2.1", "array2.2"];
List<String[]> listOfArrays = new ArrayList<String[]>();
listOfArrays.add(array1);
listOfArrays.add(array2);
assertEquals("[[array1.1, array1.2], [array2.1, array2.2]]", listOfArrays.toString());
}
Are you looking for something like this?
for(String[] sArray : new CVSReader(new StringReader(data)).readAll())
{
for(String s : sArray)
{
System.out.prinntln(s);
}
System.out.prinntln("*********");
}
I can be wrong but my suggetions are:
To separte the lines:
String[] lines = data.split("\n");
To get a java.util.List
java.util.Arrays.asList(lines)
To separate each line:
String[] fields = line.split(",");
where line will be one of the String[] lines element.
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.