Finding length of all values in an ArrayList - java

For a program I'm attempting to have a nested for loop repeat along the lines of this:
for(int i = 0;i < ArrayList.size();i++){
for(int x = 0;x <ArrayList.get(i).length();x++){
//stuff
}
}
Essentially I want to repeat a for loop for every character in every index of an ArrayList but this solution doesn't seem to work. Any help appreciated!
Edit: the arraylist will only contain strings in my case

Try using a For Each Loop such that:
int sumLength = 0;
ArrayList<String> r = new ArrayList<String>();
for(String s : r)
{
sumLength += s.length();
}
return sumLength;
That will give you the sum of all the lengths in your ArrayList

Updated code:
You can use java8 streams to tackle this issue and not to mention is is null-safe. Here is an example.
import java.util.ArrayList;
import java.util.List;
public class NestedList {
public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
list1.add("JOHN");
list1.add("JACK");
list1.add("CYTHIA");
list1.add("DANNY");
list1.stream().forEach( str -> {
char x;
for (int i = 0; i < str.toCharArray().length; i++) {
x = str.charAt(i);
//do your struff
System.out.println(x);
}
});
}
}
The stream method by Java8 will handle the list where as you can use the toCharArray which will convert the string to arrays of character to handle each character.

You can try this this way,
List<String> arrayList = new ArrayList();
arrayList.add("strings1");
arrayList.add("strings2");
for(int i = 0;i < arrayList.size();i++){
for(int x = 0;x <arrayList.get(i).length();x++){
//stuff
}
}

all your logic is correct but there is mistake with the syntax,
you use Class name instead of object reference,
ie, change ArrayList to the ArrayList reference variable in your code.
(ArrayList.size() to list.size())
change
for(int i = 0;i < ArrayList.size();i++){
for(int x = 0;x <ArrayList.get(i).length();x++){
//stuff
}
}
to
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("mango");
list.add("orange");
for(int i = 0;i < list.size();i++){
for(int x = 0;x <list.get(i).length();x++){
//stuff
}
}

Related

How to copy elements from `2d array` to `Arraylist`?

folks, what is the technique of copying elements from array to Arraylist?
public DenseBoard(T[][] x, T fillElem){
ArrayList<ArrayList<T>> myBoard = new ArrayList<ArrayList<T>>();
for(int i = 0; i < x.length; i++){
for(int j = 0; j < x[0].length; j++){
myBoard.get(i).add(j); //<<------ getting error!
}
}
}
You'll need to initialize each member of myBoard in the outer loop:
Untested Code Ahead
public DenseBoard(T[][] x, T fillElem){
ArrayList<ArrayList<T>> myBoard = new ArrayList<ArrayList<T>>();
for(int i = 0; i < x.length; i++){
myBoard.add(new ArrayList<T>); //Gotta add something to stick stuff in
for(int j = 0; j < x[0].length; j++){
myBoard.get(i).add(j); //<<------ no more error?
}
}
}
Since myBoard is an ArrayList of ArrayLists of Ts, we need to give it somewhere to put the T's. Initially, myBoard looks like this:
[] <-- empty ArrayList
So we give it somewhere to put data for each row, like this
myBoard.add(new ArrayList<T>);
Now it looks like
[ [] ] <--- ArrayList with an empty ArrayList in it, ready to accept T's
We add some T's, and end up with this
[ [T1, T2, T3] ].
And on the next iteration, we'll end up with something like this
[ [T1, T2, T3], [T4, T5, T6] ]
Hope that cleared things up.
You are getting error because your are trying to get() a value from ArrayList but not had inserted any value first. To do it your way, here is the correct code :
ArrayList<ArrayList<T>> myBoard = new ArrayList<>();
for(int i = 0; i < x.length; i++){
ArrayList<T> values = new ArrayList<>();
for(int j = 0; j < x[0].length; j++){
values.add(x[i][j]);
}
myBoard.add(values);
}
Just use the following function :
Arrays.asList(T...a)
In your case it will be done as :
ArrayList<T> myBoard = new ArrayList<>();
for(T[] arr : x){
myBoard.add(Arrays.asList(arr));
}
Try to use diamond operator <> to make code more readable
Don't reinvent the wheel, use utilities provided at least by core libraries
Make use of for-each statement where you could
Inspired from this post.
new ArrayList<Item>(Arrays.asList(array))
creates a new ArrayList of Item elements from an input array. For two-dimensionals. In this case, you tried this:
public DenseBoard(T[][] x, T fillElem){
ArrayList<ArrayList<T>> myBoard = new ArrayList<ArrayList<T>>();
for(int i = 0; i < x.length; i++){
for(int j = 0; j < x[0].length; j++){
myBoard.get(i).add(j); //<<------ getting error!
}
}
}
The problem is that the line throwing the error assumes you have an ArrayList of ArrayList, but the inner element you try to refer to is not initialized. This should be a fix:
public DenseBoard(T[][] x, T fillElem){
ArrayList<ArrayList<T>> myBoard = new ArrayList<ArrayList<T>>();
for(int i = 0; i < x.length; i++){
myBoard.add(new ArrayList<T>(Arrays.asList(x[i])));
}
//Do something with myBoard
}

Problems with returning ArrayList

I added Strings "Hello", "Cat", "Dog" into the arraylist called values passed it to the method doubleIt() which should return a list of everything doubled, i.e.
"Hello", "Hello", "Cat", "Cat", "Dog", "Dog"
But all Im getting is []. What could I do wrong here ?
import java.util.*;
public class Addition
{
public static void main(String [] args)
{
List<String> values = new ArrayList<String>();
values.add("Hello");
values.add("Cat");
values.add("Dog");
values = doubleIt(values);
System.out.println(values);
}
public static List<String> doubleIt(List<String> values)
{
List<String> temp = new ArrayList<>();
for(int i = 0; i < temp.size(); i++)
{
temp.add(values.get(i*2));
}
return temp;
}
}
Your first mistake is here...
for(int i = 0; i < temp.size(); i++)
temp.size() will be 0 when it's called the first time, you really should be using a values, but this will cause an IndexOutOfBoundsException
So you could use something like...
for (int i = 0; i < values.size(); i++) {
temp.add(values.get(i));
temp.add(values.get(i));
}
instead
First change your for loop condition from
for(int i = 0; i < temp.size(); i++)
to
for(int i = 0; i < values.size(); i++)
and then add values 2 times each.
Your for loop in doubleIt() was looping up to the wrong list size. And you were trying to multiply a string by 2, instead of adding it twice.
public static List<String> doubleIt(List<String> values)
{
List<String> temp = new ArrayList<>();
for(int i = 0; i < values.size(); i++) // <-- you needed to loop up to the size of the values list, not the temp list
{
temp.add(values.get(i));
temp.add(values.get(i));
}
return temp;
}

ArrayIndexOutOfBoundsException for my PrintList function and I have no idea why

I am writing a really simple program which automatically extends the array when the user reaches the limit of the current array.
The problem is that I am getting a java.lang.ArrayIndexOutOfBoundsException when I run my PrintList method and I really don't know why. It's working perfectly if I use a random number, which is bigger than the array (e.g. 500), but if I use
for (int i = 0; i < stringArray.length; i++)
or
for (int i = 0; i <= stringArray.length; i++)
I get a nasty exception. How do I deal with this and why am I getting it in the first place?
Thanks a lot for your help!
Here's the source code of my program:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int index = 0;
String[] randomString = new String[1];
while (index <= randomString.length) {
out.println("Enter your string");
String input = keyboard.next();
randomString[index] = input;
PrintArray(randomString);
index++;
if (index >= randomString.length) {
ExtendArray(randomString);
continue;
}
}
}
public static void ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i < stringArray.length; i++) {
stringArray[i] = secondArray[i];
stringArray = secondArray;
}
}
public static void PrintArray(String[] stringArray) {
for (int i = 0; i < stringArray.length; i++) {
out.println(" " + stringArray[i]);
}
}
Java does not work in the methods you are trying to employ. Everything in Java is passed by value, unless it is a data point in an object. What you are trying to employ is a pass by reference, which is not possible in Java.
What you are trying to do is an already existing data structure called a Vector: http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html
I would suggest doing this: (not sure if it will work properly, as my current PC doesn't have dev tools):
public static String[] ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i < stringArray.length; i++) {
secondArray[i] = stringArray[i];
}
return secondArray;
}
then calling it like so in main:
randomString = ExtendArray(randomString);
Relating to vectors, this is how it works in a Vector class:
public void incrementCount(int count){
int increment = (count * 2);
Object newElementData [] = new Object[increment];
for(int i = 0; i < count; i++)
{
newElementData[i] = elementData[i];
}
elementData = new Object[increment];
elementData = newElementData;
}
In this case, elementData is the original array, newElementData is a temp array that acts to up the bounds.
You cant get error on your PrintArray method, you get the error on the line before!
randomString[index] = input;
Because if you do this
index <= randomString.length
The last iteration is out of bounds, String of length 10 has values on 0-9. You have to change the while cycle to
index < randomString.length
Also your ExtendArray method is NOT functional!
You are supposed to swap out the randomString array for a new array with double length. You create a new array and copy the contents of the old one to the new one, but don't do anything with the new array.
I suppose you want the ExtendArray method to return the new array, and set the randomString variable to be the new array.
You need to return your second array from ExtendArray function:
public static String[] ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i <= stringArray.length; i++) {
stringArray[i] = secondArray[i];
}
return secondArray;
}
and in your main:
randomString = ExtendArray(randomString);
also your while condition should be:
while (index < randomString.length)

Removing duplicate strings from an array?

How can I remove duplicate strings from a string array without using a HashSet?
I try to use loops, but the words not delete.
StringBuffer outString = new StringBuffer("Our, aim, and, isn't, easy, you, you're, actual, and, are, aren't, and, improve, achieving, and, Obviously, and, illumination, are");
wordList = outString.toString().split(", ");
for (i = 0; i < wordList.length; i++) {
for (j = 0; j < wordList.length; j++) {
if((wordList[i]!=wordList[j])&&(j>i)){
t=true;
}
}
if(t==true){
k++;
}
}
String[] wordList1 = new String[k];
wordList = outString.toString().split(", ");
for (i = 0; i < wordList.length; i++) {
(j = 0; j < wordList.length; j++) {
if((wordList[i]!=wordList[j])&&(j>i)){
t=true;
}
}
if(t==true){
wordList1[i]=wordList[i];
}
}
1)
I think you need to use the equals operator. Try
if (!wordList[i].equals(wordList[j])){
instead of !=.
2) Also Kevin is right. You need to set t back to false.
3) Side note as pointed out by others already: To be more efficient you should start the inner loop with
for (j = i+1; j < wordList.length; j++) {
4) Another side note: Your result array is still too long. If you don't want to use a List<String> and it is ok to loose the original array you could go with a solution as suggested by Zim-Zam O'Pootertoot and set the original duplicates to null, add a counter
to count how many null values you assigned, initialize the new array with the correct size and loop a final time over the first array and copy only the non-null values into your new array.
Try this code to remove dup words:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < wordList.length; i++) {
boolean found = false;
for (int j = i+1; j < wordList.length; j++) {
if (wordList[j].equals(wordList[i])) {
found = true;
break;
}
}
// System.out.printf("Checking: [%s]%n", wordList[i]);
if (!found) {
if (sb.length() > 0)
sb.append(' ');
sb.append(wordList[i]);
}
}
System.out.printf("Unique: [%s]%n", sb);
If you are allowed to use Lists, you can define a generic method that does this fairly easily:
public <T> T[] removeDuplicates(final T[] array) {
List<T> noDuplicates = new ArrayList<T>();
for (T arrayElem : array) {
if (!noDuplicates.contains(arrayElem)) {
noDuplicates.add(arrayElem);
}
}
return (T[]) noDuplicates.toArray();
}
You probably want to set t back to false after pulling the value you want:
if(t)
{
wordList1[i]=wordList[i];
t = false;
}
Also this:
if((wordList[i]!=wordList[j])&&(j>i))
Will always return true since strings are immutable (unless you compared a string to an exact reference of itself which you disallow with j>i). You need to change it to say this:
if (!(wordList[i].equals(wordList[j]))&&(j>i))
Using .equals will compared that they contain the same string, not that they point to the exact reference of a string.
Not sure if that's the only problems or not, a bit unclear from what's given.
In your inner loop, initialize j = i + 1
if(wordlist[i] != null && wordlist[i].equals(worldlist[j])) { wordlist[j] = null; }
...and then compact the array when you're finished to remove all null values
How about using a List:
wordList = outString.toString().split(", ");
List<String> finalList = new ArrayList<String>();
for(String val : wordList) {
if(!finalList.contains(val)) {
finalList.add(val);
}
}
A Set would be more efficient, however. If you can't use a List or a Set, and you are forced to remove the duplicates, then you will have to loop through the array each time, which will perform horribly.
Iterate through the array, and store in an auxiliary int[] or List<Integer> the indexes of duplicates that you find with your two for's.
Create a new Array, with size equal to the original one minus the size of the repeated Strings.
Iterate through your original array, if the index isn't on your auxiliary list, set it to your new Array.
The best and most effective method is to suppose arr is the array that contains strings and can have duplicate values:
Arrays.sort(arr);
int l = 0;
for (int a = 0; a < arr.length; a++) {
if (a == arr.length - 1)
l++;// its a unique value
else if (!(a[a + 1].equals(arr[a])))
l++;// its also a unique
}
String newArray[] = new String[l];
l = 0;
for (int a = 0; a < arr.length; a++) {
if (a == arr.length - 1)
newArray[l] = arr[a];
else if (!(a[a + 1].equals(arr[a]))) {
newArray[l] = arr[a];
l++;
}
}
Try this...
public class RemoveDupsStringArray {
public static void main(String[] args) {
String[] withDuplicates = new String[] {"one","one","two","three","one","three","three"};
String[] withoutDuplicates = new String[] {"one","two","three"};
removeDuplicates(withDuplicates);
removeDuplicates(withoutDuplicates);
}
private static void removeDuplicates(String[] array) {
int[] occurence = new int[array.length];
for (int i = 0; i < array.length; i++) {
for(int j=i+1;j<array.length;j++){
if(array[i]==array[j]){
occurence[j]=j;
}
}
}
int resultLength=0;
for(int i=0;i<occurence.length;i++){
if(occurence[i]==0){
resultLength++;
}
}
String[] result=new String[resultLength];
int index=0;int j=0;
for(int i=0;i<occurence.length;i++){
index = occurence[i];
if(index==0){
result[j]= array[i];
j++;
}
}
for(String eachString : result){
System.out.println(eachString);
}
}
}

compare two array of string and store the result in another array

I want to compare two arrays and store the difference in another array
For example the two arrays might be
String[] a1 = { "cat" , "dog" };
String[] a2 = { "cat" , "rabbit" };
The resultant array would be like this
{ "rabbit" }
I use this code, but it does not work
int n = 0;
for (int k = 0; k <= temp.length; k++)
{
for (int u = 0; u <= origenal.length; u++)
{
if (temp[k] != origenal[u] && origenal[u] != temp[k])
{
temp2[n] = temp[k];
System.out.println(temp[u]);
n++;
}
}
}
This should do the trick.
String[] result = new String[100];
Int k = 0;
Boolean test = true;
for(i=0; i < a1.length; i++){
for(j=0; j < a2.length; j++){
if(a2[i].equals(a1[i])) continue;
test = false
}
if(test == false) result[k++] = a1[i];
}
I think that this may be what you are looking for. Note that it will only add to the third 'array' if the value exist in second array but not in first. In your example only rabbit will be stored, not dog (even though dog does not exist in both). This example could possibly be shortened but I wanted to keep it like this so it is easier to see what is going on.
First import:
import java.util.ArrayList;
import java.util.List;
Then do the following to populate and analyze the arrays
String a1[] = new String[]{"cat" , "dog"}; // Initialize array1
String a2[] = new String[]{"cat" , "rabbit"}; // Initialize array2
List<String> tempList = new ArrayList<String>();
for(int i = 0; i < a2.length; i++)
{
boolean foundString = false; // To be able to track if the string was found in both arrays
for(int j = 0; j < a1.length; j++)
{
if(a1[j].equals(a2[i]))
{
foundString = true;
break; // If it exist in both arrays there is no need to look further
}
}
if(!foundString) // If the same is not found in both..
tempList.add(a2[i]); // .. add to temporary list
}
tempList will now contain 'rabbit' as according to the specification. If you necessary need it to be a third array you can convert it to that quite simply by doing the following:
String a3[] = tempList.toArray(new String[0]); // a3 will now contain rabbit
To print the content of either the List or Array do:
// Print the content of List tempList
for(int i = 0; i < tempList.size(); i++)
{
System.out.println(tempList.get(i));
}
// Print the content of Array a3
for(int i = 0; i < a3.length; i++)
{
System.out.println(a3[i]);
}

Categories