adding String array into ArrayList - java

I want to append a and b string arrays to arrayList. But "1.0" have to be "1" using with split. Split method returns String[] so arrayList add method does not work like this.
Can you suggest any other way to doing this ?
String[] a = {"1.0", "2", "3"};
String[] b = {"2.3", "1.0","1"};
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add(a[0].split("."));

arrayList.add(a[0].split("\\.")[0]);

Should be as below
arrayList.add(a[0].split("\\.")[0]);

Split method returns an array. You have to access to his position to get the number.
arrayList.add(a[0].split("\\.")[0]);
You can also use substring method:
arrayList.add(a[0].substring(0, 1));

Access first element of that array like this :
for (int i = 0; i < a.length; i++) {
if (a[i].contains("."))
arrayList.add(a[i].split("\\.")[0]);
else
arrayList.add(a[i]);
}

Why split it?. Just use a replaceAll(), it will be more efficient as it won't create an array of Strings.
public static void main(String[] args) {
String[] a = { "1.7", "2", "3" };
List<String> arrayList = new ArrayList<String>();
for (int i = 0; i < a.length; i++) {
arrayList.add(a[i].replaceFirst("\\..*", "")); // escape the . (match it as a literal), then followed by anything any number of times.
}
System.out.println(arrayList);
}
O/P :
[1, 2, 3]

If you use Java 8,
String[] a = {"1.0", "2", "3"};
List<String> list = Arrays.stream(a).map(s -> s.split("\\.")[0]).collect(Collectors.toList());
// OR
List<String> list2 = Arrays.stream(a).map(s -> {
int dotIndex = s.indexOf(".");
return dotIndex < 0 ? s : s.substring(0, dotIndex);
}).collect(Collectors.toList());

This is working properly for me: arrayList.add(a[0].split("\\.")[0]);

Related

How to split strings of list into string array

I have a list that contains ("One.two.three", "one.two.four"). I want to save then in a string array as
One
two
three
one
two
four
What is the logic behind it?
You should be using java 8 to run this code. Just take those strings and split them on "."
split method of java need regex so to match "." you need "\.".Then transform array to list, then add words to list.
public static void main(String[] args) {
List<String> words = new ArrayList<String>();
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("one.two.four");
list.stream().forEach(str -> {
words.addAll(Arrays.asList(str.split("\\.")));
});
System.out.println(words.toString());
//output : [One, two, three, one, two, four]
}
For java 8+, you can use flatmap as -
String[] words = list.stream().flatMap(str -> Arrays.stream(str.split("\\."))).toArray(String[]::new);
If you are talking about the static arrays it is important to know array size to avoid "index is out of bounds" exception.
This way, I provide the solution that counts the number of words and then creates output s array to save every word.
We can use the String.split() function to get the single words we adding to output array:
String[] a = {"One.two.three", "one.two.four"};
int count = 0;
for (int i = 0; i < a.length; i++) { //skip this loop if you know the wanted array size
count += a[i].split("\\.").length;
}
String[] s = new String[count];
int k = 0;
for (int i = 0; i < a.length; i++) {
String[] b = a[i].split("\\.");
for (int j = 0; j < b.length; j++) {
s[k++] = b[j];
}
}
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
Try this.
FOR JAVA 1.8+
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
list.forEach(string -> {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
});
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}
UPTO JAVA 1.7
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
for (String string : list) {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
}
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}
If you are below Java 8 you can use this snippet:
public class Main {
public static void main(String[] args) throws Exception {
List<String> originalList = new ArrayList();
List<String> finalList = new ArrayList();
originalList.add("One.two.three");
originalList.add("One.two.four");
for(String myString : originalList) {
//The \\ is to scape the dot
finalList.addAll(Arrays.asList(myString.split("\\.")));
}
//Creates an array from the list
String[] theArray = finalList.toArray(new String[finalList.size()]);
}
}
Finally, theArray will contain:
[One, two, three, one, two, four]
Take a look at the docs about splitting an string into parts

ArrayList<String> in Java, [€14,€55,€500]

I have a list of webElement stored in an ArrayList of strings as below:
ArrayList<String> prints out [€300, €34, €56]
How do i remove the € sign?.
I have tried remove() and other method but they won't work. Its an ArrayList though.
Just iterate through your list and use String::replaceAll
List<String> list = new ArrayList <String>();
list.add("$123");
list.add("$345");
list.add("12345");
for (String s : list) {
System.out.println(s.replaceAll("^\\$", ""));
}
If you want to update the value in the List you can use List::set
It is not really clear what do you want. A new list with trimmed elements, just printing the elements w/o the Euro sign or something else? Is the Euro at the beginning of any element, can it occur multiple times? Etc... Here is just an idea:
List<String> list = Arrays.asList("€14", "€55", "€500");
System.out.println(list);
List<String> trimmedList =
list.
stream().
map(s -> s.startsWith("€") ? s.substring(1) : s).
collect(Collectors.toList());
System.out.println(trimmedList);
It prints:
[€14, €55, €500]
[14, 55, 500]
You can also use this regex,
List<String> myList = new ArrayList<String>();
myList.add("$14");
myList.add("$55");
myList.add("$500");
System.out.println(myList);
for (int i = 0; i < myList.size(); i++) {
myList.set(i, myList.get(i).replaceAll("^[^\\d]+", ""));
}
System.out.println(myList);
Demo
you can use replaceAll("^\\$", "") on your ArrayList.
I would iterate through the elements and just cut off the first character (assuming the euro sign is in every single one)
List<String> myList = new ArrayList<>();
...
for (int i = 0; i < myList.size(); i++) {
myList.set(i,myList.get(i).substring(1));
}
Alternative solution in the event that the first character is not always the euro symbol.
List<String> myList = new ArrayList<>();
...
for (int i = 0; i < myList.size(); i++) {
myList.set(i,myList.get(i).replace((char)8364,(char)0));
}
Try with this using Java 8 stream api.
List<String> prices = Arrays.asList("€300", "€34", "€56");
prices = prices.stream().map(s -> s.substring(1)).collect(Collectors.toList());
System.out.println(prices); // [300, 34, 56]
Loop through your price list and replace the euro sign like :
for (String price : prices) {
price.replaceAll("^\\$", "");
}
Below code works as per your requirement.
List<String> myList = new ArrayList<String>();
myList.add("#14");
myList.add("#55");
myList.add("#500");
System.out.println(myList);
for (int i = 0; i < myList.size(); i++) {
myList.set(i,myList.get(i).substring(1));
}
System.out.println(myList);
Output :
[#14, #55, #500]
[14, 55, 500]

How to Convert an String array to an Int array?

I have made research for a couple hours trying to figure out how to convert a String array to a Int array but no luck.
I am making a program where you can encrypt a message by using three rotors. I am able to type a message and get the index number for the first rotor (inner rotor) to encrypt into the third rotor (outer rotor). The problem is the index number is in a string array which I want it to become a int array.
Yes, I have tried
int[] array == Arrays.asList(strings).stream()
.mapToInt(Integer::parseInt).toArray();
or any form of that. I'm not unsure if I have java 8 since it doesn't work, but it gives me an error.
Can someone help me how to convert a String array to a Int array?
public void outerRotorEncrypt() {
String[] indexNumberSpilt = indexNumber.split(" ");
System.out.println("indexNumber length: " + indexNumber.length()); //test
System.out.println("indexNumberSpilt length: " + indexNumberSpilt.length); //test
System.out.println("Index Number Spilt: " + indexNumberSpilt[3]); //test
System.out.println("");
System.out.println("");
System.out.println("testing from outerRotorEncrypt");
System.out.println("");
for(int i = 1; i < indexNumberSpilt.length; i++){
secretMessage = secretMessage + defaultOuterRotorCharacterArray[indexNumberSpilt[i]];
}
System.out.println("Secret Message from outerRotorEncrypt: " + secretMessage);
}
If you are using Java8 than this is simple way to solve this issue.
List<?> list = Arrays.asList(indexNumber.split(" "));
list = list.stream().mapToInt(n -> Integer.parseInt((String) n)).boxed().collect(Collectors.toList());
In first Line you are taking a generic List Object and convert your array into list and than using stream api same list will be filled with equivalent Integer value.
static int[] parseIntArray(String[] arr) {
return Stream.of(arr).mapToInt(Integer::parseInt).toArray();
}
So take a Stream of the String[]. Use mapToInt to call Integer.parseInt for each element and convert to an int. Then simply call toArray on the resultant IntStream to return the array.
Have you tried:
int[] array = new int[indexNumberSpilt.lenght()];
for ( int i=0;i<indexNumberSpilt.lenght();i++ ){
array[i] = Integer.valueOf(indexNumberSpilt[i]);
}
int[] array == Arrays.asList(strings).stream()
.mapToInt(Integer::parseInt).toArray();
The reason why it's giving an error is because of ==, changing that to = (assignment operator) should work, e.g.:
String[] input = new String[]{"1", "2"};
int[] array = Arrays.asList(input).stream()
.mapToInt(Integer::parseInt).toArray();
for(int a : array){
System.out.println(a);
}
Small Demo
String[] string = { "0", "1", "11", "0", "0", "1", "11", "0", "0", "1",
"11", "0" };
List<String> temp = Arrays.asList(string);
List<Integer> temp1 = new ArrayList<Integer>();
for (String s : temp) {
temp1.add(Integer.parseInt(s));
}
int[] ret = new int[temp1.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = temp1.get(i).intValue();
}
System.out.println(Arrays.toString(ret));
}
int[]
If you want an int[] array:
String indexNumber = "1 2 3 4";
String[] indexNumberSpilt = indexNumber.split(" ");
int[] result = Stream.of(indexNumberSpilt).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(result));
Integer[]
String indexNumber = "1 2 3 4";
String[] indexNumberSpilt = indexNumber.split(" ");
Integer[] result = Stream.of(indexNumberSpilt).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(result));
Both examples will print:
[1, 2, 3, 4]

Modify String objects in a static array

I want to make a for-loop to add a letter to each string object in my list. I'm just not sure how to edit the objects in the list and not the actual list.
for instance, if I wanted to add "ing" to the end of each object in my list..
I feel like it's something simple, but I've been looking through oracle forever and haven't been able to figure it out if anyone can point me in the right direction?
I could use any kind of list really.. just anything that works.
I was thinking something like,
String[] stringArray = tools.toArray(new String[0]);
for (int i = 0; i < stringArray.length; i++)
{
stringArray[i] = stringArray[i].*part that would modify would go here*
}
You cannot edit a String. They are immutable. However, you can replace the entry in the list.
ArrayList<String> list = new ArrayList<>();
list.add("load");
list.add("pull");
for (int i = 0; i < list.size(); ++i) {
list.set(i, list.get(i) + "ing");
You updated your question to specify a static array:
stringArray[i] = stringArray[i] + "ing";
The right side of the assignment is performing a String concatenation which can be done with the + operator in Java.
You can use StringBuilder for this purpose.
public static void addIng(String[] arr) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.setLength(0);
sb.append(arr[i] + "ing");
arr[i] = sb.toString();
}
}
Strings are immutable in java; they can't be modified once created.
Here it seems you have a few options; you can create a method that takes your list and returns a new list, by appending 'ing' to the end of each string in the list.
Alternatively, if you need to keep a reference to the original list, you can loop over the contents of the list (ArrayList?) and pop each string out, create a new string with the appended 'ing', and replace in the list.
Something like
List<String> list = new ArrayList<>();
list.add("testing");
for(String s:list){
s=s+"ing";
}
Please take a look below samples.
//Java 8 code.
List<String> oldList = Arrays.asList("a", "b");
List<String> newList = oldList.stream().map(str -> new StringBuilder(str).append("ing").toString()).collect(Collectors.toList());
System.out.println(oldList); // [a, b]
System.out.println(newList); // [aing, bing]
// Java 7 or below.
List<String> oldList = Arrays.asList("a", "b");
List<String> newList = new LinkedList<String>();
for (String str : oldList) {
newList.add(new StringBuilder(str).append("ing").toString());
}
System.out.println(oldList); // [a, b]
System.out.println(newList); // [aing, bing]

Spliting string by character, returning with null values

I have below code
String str= new String("aaa,,bbb,,ccc,");
String[] strArray= str.split(",");
From this I am getting below values in strArray
strArray = [aaa,'',bbb,'',ccc];
But I want below output
strArray = [aaa,null,bbb,null,ccc,null];
I have written my own function to do this, but I want to know is there any standard method which can give this output?
If yes then please suggest
If no then please suggest if any improvement for below code.
public List<String> splitStr(String str, char character) {
List<String> list = null;
if (StringUtil.isNotEmpty(str)) {
list = new ArrayList<String>();
int i;
char ch;
int characterIndex, loopStartingIndex = 0;
if (str.charAt(0) == character) {
list.add(null);
} else {
list.add(str.substring(0, str.indexOf(character)));
loopStartingIndex = str.indexOf(character);
}
int length = str.length();
for (i = loopStartingIndex; i < length; i++) {
ch = str.charAt(i);
if (ch == character) {
characterIndex = str.indexOf(character, i+1);
if (characterIndex == i+1 || characterIndex == -1) {
list.add(null);
} else {
list.add(str.substring(i+1, characterIndex));
i = characterIndex-1;
}
}
}
}
/*for (String s : list) {
System.out.println(s);
}*/
return list;
}
Edit:
I had tested the code for abc,,,, string with str.split(",") method and I got [abc] as output so I thought aaa,,bbb,,ccc will give me 3 values by split method. But it is giving [aaa,'',bbb,'',ccc] skipping ending commas.
You can pass a negative value to String.split(String, int) like
String str = "aaa,,bbb,,ccc,";
String[] strArray = str.split(",", -1);
System.out.println(Arrays.toString(strArray));
Output is
[aaa, , bbb, , ccc, ]
This is helpfully documented in the linked javadoc as,
If n is non-positive then the pattern will be applied as many times as possible and the array can have any length
Edit
public static void main(String[] args) {
String str = "aaa,,bbb,,ccc,";
String[] strArray = str.split(",", -1);
for (int i = 0; i < strArray.length; i++) {
if (strArray[i].isEmpty()) {
strArray[i] = null;
}
}
System.out.println(Arrays.toString(strArray));
}
Output is
[aaa, null, bbb, null, ccc, null]
how about something simpler
String str= new String("aaa,,bbb,,ccc,");
String[] strArray= str.split(",", -1);
This -- ^^
write a like :
String str= new String("aaa,,bbb,,ccc,");
String[] strArray= str.split(",");
for(int i=0;i<strArray.length;i++)
System.out.print(strArray[i]);
or
System.out.print(Arrays.toString(strArray));
output:
[aaa, , bbb, , ccc]
The following code
String str = "aaa,,bbb,,ccc";
String[] strArray = str.split(",");
System.out.println(Arrays.toString(strArray));
outputs [aaa, , bbb, , ccc], so the array has 5 elements, not 3 as you claim. The only thing you have to do is loop through the array and replace empty strings by null references to get what you want.
You can pass a negative number as the second argument of split, but this only effects empty strings at the end of the array. With a negative number, the empty string at the end are also included. That is,
"aaa,,bbb,".split(",")
returns ["aaa","","bbb"], while
"aaa,,bbb,".split(",",-1)
returns ["aaa","","bbb",""].

Categories

Resources