Skipping a particular value of ArrayList during printing - java

My Code is as follows:
ArrayList<Integer> al = new ArrayList();
al.add(1);
al.add(2);
al.add(3);
al.add(3);
al.add(4);
I want the following pattern during printing:
[1,2,4]
I tried both for loop and Iterator but I am not getting the desired output.
Help me to sort out!
I found the solution and that is
for(int i=0;i<al.size();i++) {
if(al.get(i)!=3)
System.out.println(al.get(i));
}
thanks for your help
Now I want to get the same output, not through printing but by deleting elements of ArrayList, I tried with the same condition but I got exception
and the answer is
Iterator<Integer> iter = al.iterator();
while (iter.hasNext()) {
if (iter.next().intValue() == 3) {
iter.remove();
}
}
System.out.println(al);

Step through all the items in the ArrayList and test if they are equal to 3, if they are not, print them.
for (Integer i : al) //for each Integer in the al list
{
if (!i.equals(3)) //if it is NOT (!) equal to 3
{
System.out.println(i); //then print it
}
}
Obviously if you want to skip more than just the number 3 you will need to expand the condition the if uses.
Note on removing elements from the list
If you try and remove from the list within the loop using this method you will encounter problems with ConcurrentAccessException, this is dealt with in this question.

If you want to get the list element and as per your output it seems you want to print 1 and even numbers in the list
for(int i=0; i< a1.size(); i++) //iterate over List
{
if(a1.get(i)%2=0 || a1.get(i) == 1) //print if 1 or even
System.out.println(a1.get(i));
}

You can also use the forEach method (Java 8):
al.forEach(v -> {if(v!=3) System.out.println(v);});

add the required skipping values in a list and check against that list before printing
My code:run and give comment(views please)
import java.util.*;
public class Mycode{
public static void main(String []args){
ArrayList<Integer> al = new ArrayList();
al.add(1);
al.add(2);
al.add(3);
al.add(3);
al.add(4);
ArrayList<Integer> al1 = new ArrayList();
al1.add(3);
al1.add(2);
int flag=0;
for(int j=0; j< al.size(); j++)
{
flag=0;
for(int i=0; i< al1.size(); i++)
{
if(al.get(j)==al1.get(i))
flag=1;
}
if(flag==0)
System.out.println(al.get(j));
}
}
}

Related

ArrayList iteration specific list

I have an arraylist in which
ArrayList<ArrayList<String>> listofItems=new ArrayList<ArrayList<String>>();
in the list of items I have items like this
[[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][22]]
how to iterate and store in another array these values split into two like
[1,2,3,4,5,6,7,8,9,10,11] and [11,12,13,14,15,16,17,18,19,20,21,22]. I have used advanced for loop
for(ArrayList<String> list:listofItems)
{
for (String s:list)
{
//I dont know how to add logic here.
}
}
I am assuming here that both lists will also hold string type data.If you want Integer type,you can parse while adding.
ArrayList<ArrayList<String>> listofItems = new ArrayList<ArrayList<String>>();
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
for (ArrayList<String> list : listofItems) {
for (String s : list) {
// there shud be some condition how much elements you want in a
// list or some condition
// to decide in which list we need to add item
if (list.size() < 12)
list1.add(s);
else
list2.add(s);
}
}
Use something like that:
if (yourlist.size()>0) {
List<String> first = yourList.subList(0, (int)Math.ceil(yourlist.size()/2.0));
List<String> second = yourList.subList((int)Math.ceil(yourlist.size()/2.0), yourlist.size());
}
Would be separate your list in 2 lists divided in the half.
You can use this code to store your list into another list.
List<String> stringList = new ArrayList<String>();
for(ArrayList<String> list:listofItems) {
for (String s:list) {
stringList.add(s);
}
}
In this case, when you add info to listOfItems, you should try example like this
for(int i = 0; i< 2; i++){
for(int j = 0; j < n; j++){
/// add util break n
lists.get(i).add(strTemp);
}
}
You can change i < 2 into any number you want. I only make this sample for you.

Class not showing up in run configurations?

I have a simple class that takes out items that were already in another array from the first array, by putting it into a list. Whenever I run this program though, another program that I created starts to run. I have tried to change the run configuration as well, but it doesn't show up on the list..? Here is the code:
package collections;
import java.util.*;
public class Arraystring {
public static void main(String [ ] args, int Collection, int String){
String[] things = { "eggs", "lasers", "hats", "pie" };
List<String> list1 = new ArrayList<String>();
for (String x : things){ //enhanced for loop
list1.add(x);
}
System.out.println(list1);
String[] thingstwo = { "lasers", "hats" };
List<String> list2 = new ArrayList<String>();
for(int i = 0;i<list2.size(); /* size for list, length for array */ i++) //regular for loop
{
list2.add(thingstwo[i]);
}
//print list one
for(int i = 0;i<list1.size(); /* size for list, length for array */ i++) //regular for loop
{
System.out.println(list1.get(i)); //Use .get for lists instead of []
}
editlist(list1, list2);
System.out.println();
//print list one
for(int i = 0;i<list1.size(); /* size for list, length for array */ i++) //regular for loop
{
System.out.println(list1.get(i)); //Use .get for lists instead of []
}
}
public static void editlist(Collection<String> l1, Collection<String> l2){
Iterator<String> it = l1.iterator(); //Goes through each list item by item
while (it.hasNext()){
if(l2.contains(it.next())){
it.remove();
}
System.out.println(it);
}
}
}
Thanks for helping, I really appreciate it.
You can execute Run file command from menu/shortcut or change main project in the IDE.
Specify yours IDE and proper shortcuts/commands would be given to you.
Upd.
You have error in yours logic:
String[] thingstwo = {"lasers", "hats"};
List<String> list2 = new ArrayList<>();
for (int i = 0; i < list2.size(); i++)
list2.add(thingstwo[i]);
Look at it line-by-line:
String[] thingstwo = {"lasers", "hats"};
Defining array, ok.
List<String> list2 = new ArrayList<>();
Defining list of strings, ok.
for (int i = 0; i < list2.size(); i++)
Looping throug items of list list2, not ok. list2 at this point is empty. Assuming you wanted to loop through thingstwo and add it's items to list2, so fixing the code:
for (int i = 0; i < thingstwo.length; i++)
And...
list2.add(thingstwo[i]);
Adding i-th item of thingstwo to list2, ok.
Running:
[eggs, lasers, hats, pie]
eggs
lasers
hats
pie
eggs
pie

How can I fix this exception

Here is my code to distinguish the differences between two txt files. The only problem is i get an out of bounds exception if i dont subtract 1 from the arrayList, so right now it is not running for all of the elements, how do i fix this?
import java.io.*;
import java.util.*;
public class myfilereader
{
public static void main (String[] args) throws java.io.IOException
{
int temp = 0;
ArrayList<String> ArrayList1 = new ArrayList<String>();
ArrayList<String> ArrayList2 = new ArrayList<String>();
ArrayList<String> ArrayList3 = new ArrayList<String>();
try
{
Scanner File1 = new Scanner(new File("/Users/Home/Desktop/File1.txt"));
while (File1.hasNext())
{
ArrayList1.add(File1.next());
}
Scanner File2 = new Scanner(new File("/Users/Home/Desktop/File2.txt"));
while (File2.hasNextLine())
{
ArrayList2.add(File2.next());
}
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
for (String ArrayList : ArrayList1)
{
System.out.println("File 1: " + ArrayList1);
}
for (String ArrayList : ArrayList2)
{
System.out.println("File 2: " + ArrayList2);
}
if(ArrayList1.size()>ArrayList2.size())
{
for(int i=0; i<ArrayList1.size()-1; i++)
{
if(ArrayList1.get(i).equals(ArrayList2.get(i)))
{
temp++;
}
}
}
if(ArrayList2.size()>ArrayList1.size())
{
for(int i=0; i<ArrayList2.size()-1; i++)
{
if(ArrayList2.get(i).equals(ArrayList1.get(i)))
{
temp++;
}
}
}
if(temp == 0)
System.out.println("The files are the same.");
else
System.out.println("There are " + temp + " differences between the files");
}
}
This is the problem:
if(ArrayList1.size()>ArrayList2.size())
{
//ArrayList1 is bigger!!!!
for(int i=0; i<ArrayList1.size()-1; i++)
{
if(ArrayList1.get(i).equals(ArrayList2.get(i)))
// ArrayList2 does not contain as many elements as ArrayList1
{
temp++;
}
}
}
therefore. You can have your loop from 0 -> ArrayList.size() but be sure to use the shorter list as the limit for the loop! :-)
Alternatively, you can replace:
for(int i=0; i<ArrayList1.size()-1; i++)
With:
for (String s : ArrayList1)
This is called a for-each loop and can be used for more readable simpler iteration.
As Sara Seppola already mentioned, you need to use the smallest of the two sizes to compare the elements in the two lists. Currently, you're using the biggest of the two, which guarantees that you'll go out of bounds on the smaller list.
Also, you should be using ArrayList1.size() and not ArrayList1.size()-1 in your loop limits, as the strictly less than check in your loop condition currently causes i to iterate from 0 to ArrayList1.size()-2 - which is one too short. Again, the index-out-of-bounds is not caused by the -1, but rather because of the incorrect size used in the condition.
Finally, you're not accounting for the case where the lists have equal sizes. Currently, your code gives "The files are the same" since there's not if-test which passes when ArrayList1.size() == ArrayList2.size().
if(ArrayList1.size() >= ArrayList2.size())
{
// Here, ArrayList1.size() >= ArrayList2.size()
// Use the smallest size as limit so we stay in bounds for both
// In this case, that's ArrayList2.size()
// When the lists have equal length, both sizes could be used
// as limit so it doesn't really matter whether you use
// > or >= in the test of the above if-statement
for(int i=0; i<ArrayList2.size(); i++)
{
if(ArrayList1.get(i).equals(ArrayList2.get(i)))
{
temp++;
}
}
}
else
{
// Here, ArrayList1.size() < ArrayList2.size()
// so use ArrayList1.size() as the limit
for(int i=0; i<ArrayList2.size(); i++)
{
if(ArrayList2.get(i).equals(ArrayList1.get(i)))
{
temp++;
}
}
}
There's still an error in your code though: you're only comparing corresponding elements. What about the extra elements from the larger list? Those should be counted as differences as well.
A quick fix would be to simply subtract the two sizes to get the number of extra elements in the bigger list, and use that as initial value for the number of difference:
if(ArrayList1.size() >= ArrayList2.size())
{
temp = ArrayList1.size() - ArrayList2.size();
// [for loop]
}
else
{
temp = ArrayList2.size() - ArrayList1.size();
// [for loop]
}
Of course, you could still simplify your code. You could use Math.min(ArrayList1.size(), ArrayList2.size()) to get the smallest of the two sizes and remove the duplicated loop. You could also use Math.abs(ArrayList1.size() - ArrayList2.size()) to get the number of extra elements, regardless whether ArrayList1 or ArrayList2 is the largest. I'll leave that as an exercise for the reader. ;-)
if(ArrayList1.size()>ArrayList2.size())
{
for(int i=0; i<ArrayList1.size()-1; i++)
{
if(ArrayList1.get(i).equals(ArrayList2.get(i)))
{
temp++;
}
}
}
Here you first check if ArrayList1 has more items than ArrayList2, and then you loop over the bigger ArrayList1, using get(i) on ArrayList1 as well as ArrayList2.
Because ArrayList1 has more items than ArrayList2, eventually you will get an item from at index X from ArrayList1 that you cannot get from ArrayList2 because ArrayList2 contains less items.
Example: ArrayList1 has 10 items and ArrayList2 has 9 items. You enter the if because 10 > 9. Then at the last iteration in the for loop you do ArrayList1.get(9) which is fine because it has 10 items and this gets the 10th, but ArrayList2.get(9) will fail because it has only 9 items. 8 is the highest index you can work with.
The second if has the same problem, but the other way around.
A fix to stop the error from occurring would be to
for(int i = 0; i < ArrayList2.size(); i++)
{
...
This might not do what you want your code to do, but the error will be gone.

Iterate through an ArrayList of ArrayLists in Java

I have the following ArrayList...
ArrayList<ArrayList<Integer>> row1 = new ArrayList<ArrayList<Integer>>();
The following arraylists are added to it....
row1.add(cell1);
row1.add(cell2);
row1.add(cell3);
row1.add(cell4);
row1.add(totalStockCell);
I want to iterate through the arraylist row1 and print the contents.
Would a loop within a loop work here?
E.g.
while(it.hasNext()) {
//loop on entire list of arraylists
while(it2.hasNext) {
//each cell print values in list
} }
This is the canonical way you do it:
for(List<Integer> innerList : row1) {
for(Integer number : innerList) {
System.out.println(number);
}
}
for (ArrayList<Integer> list : row1)
{
for (Integer num : list)
{
//doSomething
}
}
Java enhanced-for loops use an iterator behind the scenes.
If you want to use Iterator, nested loops will work:
Iterator<ArrayList<Integer>> it = row1.iterator();
while(it1.hasNext())
{
Iterator<Integer> itr = it.next().iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
Here some functional approach:
ArrayList<ArrayList<Integer>> row1 = new ArrayList<>();
row1.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
row1.add(new ArrayList<>(Arrays.asList(4, 5, 6)));
row1.stream().flatMap(Collection::stream).forEach(System.out::println);
Old question, but I am just curious why no one has mentioned this way,
for(int i=0; i<list.size(); i++) {
for(int j=0; j<list.get(i).size(); j++) {
System.out.print(list.get(i).get(j) + " ");
}
System.out.println();
}
This is same as accessing a matrix in 2D arrays.

printing elements of array in arraylist in java

I do have this code, and I would like to print out all the array's values of Arraylist.
thanks for your help in advanced.
here is my code:
for (int i = 0; i <count; i++) {
System.out.println("list #" + i);
for (int j = 0; j < list[i].size(); j++) {
list[i].get(j);
System.out.println("elements of array in arraylist "+list[i].get(j));
}
}
For printing elements of an array stored in arraylist,you will have to to do the following:
for each element of arraylist
get array from arraylist
for each array element in array
print array element.
You seemed to be iterating array of List type instead.
Edit your code with further detail on your data structure
for (Object[] array : list)
for (Object o : array)
System.out.println("item: " + o);
See if this can work for you. I think it's simpler:
int numLists = 10; // Or whatever number you need it to be.
ArrayList [] arrayOfLists = new ArrayList[numLists];
// you realize, of course, that you have to create and add those lists to the array.
for (ArrayList list : arrayOfLists) {
System.out.println(list);
}
I'd wonder why you don't prefer a List of Lists:
List<List<String>> listOfLists = new ArrayList<List<String>>();
// add some lists of Strings
for (List<String> list : listOfLists) {
System.out.println(list);
}
Below code works fine for me
public class Solution
{
public static void main(String[] args)
{
int T,N,i,j,k=0,Element_to_be_added_to_the_array;
Scanner sn=new Scanner(System.in);
T=sn.nextInt();
ArrayList<Integer>[] arr=new ArrayList[T];
for(i=0;i<T;i++)
{
arr[k]=new ArrayList<Integer>();
N=sn.nextInt();
for(j=0;j<N;j++)
{
Element_to_be_added_to_the_array=sn.nextInt();
arr[k].add(Element_to_be_added_to_the_array);
}
k++;
}
//Printing elements of all the arrays contained within an arraylist
for(i=0;i<T;i++)
{
System.out.println("array["+i+"]");
for(j=0;j<arr[i].size();j++)
{
System.out.println(arr[i].get(j));
}
}
}
}

Categories