I have a 2d ArrayList which stores objects, i want to check if a certain object exists in any of of the rows, and if not add a new row, and search that object in future checks. eg.
ArrayList<List<Object>> list = new ArrayList<>();
for(List<Object> o : list) {
if(!o.contains(object){
ArrayList<Object> newList = new ArrayList<>();
newList.add(object);
list.add(newList);
}
}
This gives me a 'ConcurrentModificationException' but I can't find another way to do it.
Thanks in advance.
list.add(newList); this line should be outside your for loop. You are trying to modify your list while iterating on it. Just keep adding elements to newList in the for loop. Add the line list.add(newList); after the for loop.
You cannot change a List while you are iterating over its items.
What you can do is:
ArrayList<List<Object>> list = new ArrayList<>(); // in practice this would not be an empty list, but it would, as in your example, contain all items
ArrayList<List<Object>> newRows = new ArrayList<>();
for(List<Object> o : list) {
if(!o.contains(object){
ArrayList<Object> newList = new ArrayList<>();
newList.add(object);
newRows.add(newList);
}
}
list.addAll(newRows);
You have to replace:
for(List o : list) {
with:
for(int i = 0; i < list.size(); i++) {
List o = list.get(i);
Just be careful when you do this to handle how you modify the list. In this case there should be no problem.
Related
I am trying to grasp the concept. I have never worked with ArrayLists before (just arrays).
What I have is:
ArrayList<ArrayList<String>> movies = new ArrayList<ArrayList<String>>();
What this will look like or the way I picture it is:
[[Ratatouille, A Bug's Life], [Tangled, Zootopia, Finding Dory], [Harry Potter]]
And say the userInput = 2; then I would subtract 1 from the user input (because Array's and ArrayList's index at 0 that much I know) so userInput= 1; (based on their multiple choice selection, not very important).
Then what I want to do is take the index 1 so [Tangled, Zooptopia, Finding Dory] and loop through that index and add it to an ArrayList (not ArrayList of an ArrayList).
No need to loop - You can access an ArrayList by an index, and then use the addAll method to add all the elements of the ArrayList in that position to your result:
result.addAll(movies.get(userInput - 1));
following with following code you can iterate through an arrayList
private ArrayList<String> myArrayList = new ArrayList<>();
for(int i=0;i<myArrayList.size();i++){
myArrayList.get(i);
// Perform whatever operation here
}
Let me know if it doesn't work. And also what's the error given
The ArrayList.get(int index) method can help you out.
ArrayList myList = fullList.get(1);
would give you your desired list and you can iterate over it like:
for (String currString: myList){
//Do things with currString
}
I hope I explained it well :)
You should learn how to use Java Lambdas. you can use a lambda to iterate through an ArrayList since ArrayLists are Iterable.
ArrayList<ArrayList<String>>arrayListofarrayList = new ArrayList<ArrayList<String>>();
arrayListofarrayList.forEach((arrayList) -> {System.out.println(arrayList.get(1));});
or
ArrayList<ArrayList<String>>arrayListofarrayList = new ArrayList<ArrayList<String>>();
arrayListofarrayList.forEach((arrayList) -> {\*code here!*\});
if you're trying nest iterations you can:
ArrayList<ArrayList<String>>arrayListofarrayList = new ArrayList<ArrayList<String>>();
arrayListofarrayList.forEach((arrayList) -> {
arrayList.forEach((item) -> {
System.out.println(item);
});
});
Declare your variable as following
private ArrayList<String> arrayList = new ArrayList<>();
Then in a method add following
for(int j=0; j < arrayList.size() ; j++){
arrayList.get(i);
// Your code goes here
}
This should work
You can use either for-each loop or simple for loop to print elements in ArrayList of ArrayList. For example,
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);list1.add(2);
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(3);list2.add(4);
ArrayList<Integer> list3 = new ArrayList<>();
list3.add(5);list3.add(6);
ArrayList<ArrayList<Integer>> listOfList = new ArrayList<>();
listOfList.add(list1);
listOfList.add(list2);
listOfList.add(list3);
// Printing elements using for-each loop
for(ArrayList<Integer> eachList : listOfList){
for(Integer elementInList : eachList){
System.out.print(elementInList + "\t");
}
System.out.println();
}
// Printing elements using for loop
for(int i = 0;i < listOfList.size();i++){
ArrayList<Integer> eachList = listOfList.get(i);
for(int j = 0;j < eachList.size();j++){
System.out.print(eachList.get(j) + "\t");
}
System.out.println();
}
Output:
I cant understand 2D arraylists, they are confusing me, I can understand 2D arrays however as I worked with them before in C and in Python as "nested lists"
can someone explain the difference between these 2 codes?
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
ArrayList<String> temp = new ArrayList<String>(); // added ()
temp.add("Hello world.");
temp.add("sup");
biDemArrList.add(temp);
ArrayList<String> it = new ArrayList<String>();
it.add("1");
it.add("0");
biDemArrList.add(it);
System.out.println(temp);
System.out.println(it);
System.out.println(biDemArrList);
and this one :
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
for (int i = 0; i < 12; i++) {
table[0][5].add("0");
}
for (int i = 0; i < 9; i++) {
table[1][1].add("1");
}
System.out.println(table[0][5]);
System.out.println(table[9][9]);
Like in C arrays of non primitive types are not initialized (only arrays of primitive types are...).
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
Here you create an array of 100 elements but you only initialize 2 Elements.
ArrayList is resizable-array implementation of the List interface. This class. Most of the developers choose Arraylist over Array as it’s a very good alternative of traditional java arrays.
You can add any object to List, e.g. null, String, Object, String[]. ArrayList<String> also is object, it's means you can add to list.
You said I have ArrayList which can add other ArrayList. The result will be ArrayList<ArrayList>>.
But we want to add only String's to inner ArrayList. And we create ArrayList<String>
So, We have list of string ArrayList<String> which can be added to other list ArrayList<ArrayList>>
ArrayList<ArrayList<String>> mainArrayList = new ArrayList<ArrayList<String>>();
ArrayList<String> subArrayList = new ArrayList<String>();
/* Added elements into subArrayList */
subArrayList.add("Yogesh");
subArrayList.add("Pawar");
ArrayList<String> subArrayList2 = new ArrayList<String>();
/* Added elements into subArrayList2 */
subArrayList2.add("Java");
subArrayList2.add("Programmer");
/* Adding elements into mainArrayList */
mainArrayList.add(subArrayList);
mainArrayList.add(subArrayList2);
for (int i = 0; i < mainArrayList.size(); i++) {
for (int k = 0; k < mainArrayList.get(i).size(); k++) {
System.out.print(" " + mainArrayList.get(i).get(k));
}
System.out.println();
}
The difference between
List of List
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
and
Array of Array of List
ArrayList[][] table = new ArrayList[10][10];
Is that the second one is not actually two-dimensional, it is three-dimensional. You end up with 10 Arrays of length 10 that you can put ArrayLists into. Where as in the List of List example you have a List you can put other Lists into.
Using the Object[][] or primitive[][] you have to allocate the 2D array with exact number of "rows" and "columns" like new Object[2][8].
On the other hand with ArrayList<ArrayList<...>> try to understand the following code:
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<>();
ArrayList<String> a0 = new ArrayList<>();
a0.add("string_1");
ArrayList<String> a1 = new ArrayList<>();
a1.add("strfdfas");
a1.add("adfadsfasdfasdfasfaf");
biDemArrList.add(a0);
biDemArrList.add(a1);
biDemArrList.stream().forEach(System.out::println);
The first "row" has one element, and the second one has two elements. This is only an example... With arr[][] you cannot achieve this.
What is reason behind this not sure, But i would share my experience here,
Array is the fixed size of data structure, once we initialize the array we can't modify the size. To resolve this we have ArrayList comes to picture. Arraylist has variable lenght.
In your second code snippet, if you are looking for fixed sized of 2D ArrayList, I would suggest to go 2D Arrays.
If you want to get benefit of Collection features, later you can convert Arrays to ArrayList object.
I have an array list
ArrayList<String> list=new ArrayList<String>();
list.add("Apple");
list.add("Ball");
list.add("Ball");
list.add("Cat");
list.add("Cat");
list.add("dog");
and I want to transfer duplicate strings to other ArrayList.
I mean 2nd array list should only contain Ball and Cat not Apple and dog.
Any kind of help is appreciated.
You can do this:
List<String> duplicates = new ArrayList<String>();
for(String str: list) {
if(Collections.frequency(list, str) > 1) {
duplicates.add(str);
}
}
duplicates will contain your duplicates
Try this:
// Custom list to ensure that one duplicate gets added to a list at most as
// opposed to n-1 instances (only two instances of a value in this list would
// be deceiving).
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Ball");
list.add("Ball");
list.add("Ball");
list.add("Ball");
list.add("Cat");
list.add("Cat");
list.add("Cat");
list.add("dog");
list.add("dog");
Set<String> set = new HashSet<>();
Set<String> setOfDuplicates = new HashSet<>();
for (String s : list) {
if (!set.add(s)) { // Remember that sets do not accept duplicates
setOfDuplicates.add(s);
}
}
List<String> listOfDuplicates = new ArrayList<>(setOfDuplicates);
You can use a Set as a way to help determine the duplicated elements then simply return an ArrayList of those elements.
public static ArrayList<String> retainDuplicates(ArrayList<String> inputList){
Set<String> tempSet = new HashSet<>();
ArrayList<String> duplicateList = new ArrayList<>();
for (String elem : inputList) {
if(!tempSet.add(elem)) duplicateList.add(elem);
}
return duplicateList.stream().distinct().collect(Collectors.toCollection(ArrayList::new));
}
call the method like so:
ArrayList<String> resultList = retainDuplicates(list);
note that I've used distinct() to remove any elements that occur more than once within the duplicateList. However, if you want to keep the duplicates regardless of theirs occurrences within the duplicateList then just perform return duplicateList; rather than return duplicateList.stream().distinct().collect(Collectors.toCollection(ArrayList::new));.
since you said your duplicates will all be next to each other, you can itterate through the list in pairs, and if the pair's elements match, there is a duplicate
here would be the general pseudo code for it
int first = 0
int second = 1
for (arraySize)
if (array[first] == array[second])
//there is a match here
newArray.add(array[first])
first += 1
second += 1
Note that this does not check the bounds of the array, which should be easy to implement yourself
now as for the second list not having duplicate items, you can simply store a variable with the last transfered item, and if the new found duplicate is the same, dont transfer it again
ArrayList<String> list=new ArrayList<String>();
list.add("Apple");
list.add("Ball");
list.add("Ball");
list.add("Cat");
list.add("Cat");
list.add("dog");
List<String> duplicateList= new ArrayList<String>();
for(String str: list) {
if(Collections.frequency(list, str) > 1) {
duplicateList.add(str);
}
}
System.out.println(duplicateList.toString());
//Here you will get duplicate String from the original list.
I have List of ArrayList Elements, see below.
List<List<String>> x = new ArrayList<List<String>>();
it contains some array list elements.
eg.
x.get(0)->[1,2,3,4],
x.get(1)->([5,6,7,8],
x.get(2)->[9,10,11,12],
x.get(3)->[13,14,15,16]
i want to access element 3 from x.get(0) or element 7 from x.get(1) how to call that??
Each element of your list is a list and has the same interface that provides List<T> methods, e.g.
T get(int index)
boolean isEmpty()
void add(T element)
etc.
You can access element from the inner list by index
List<List<String>> x = new ArrayList<List<String>>();
// ... some data initialised
String element_0_3 = x.get(0).get(3);
Be aware that each List<String> element needs to have been created before accessing it. For instance, in order to add a new String at the [0,0] coordinates:
List<List<String>> x = new ArrayList<List<String>>();
List<String> x0 = new ArrayList<>();
x0.add("foo"); // add "foo" as the first string element
x.add(x0); // add x0 as the first List<String> element
You can also read values with an enhanced for loop, without using the indexes:
List<List<String>> x = new ArrayList<List<String>>();
//...
for (List<String> ls : x) { // iteration on the x list
for (String s : ls) { // iteration on each intern list
System.out.println(s);
}
You can follow like...
List<List<String>> x = new ArrayList<List<String>>();
List<String> subX = x.get(7);
if(null != subX && subX.size() != 0) {
String element = subX.get(0);
}
//To directly access any list member using for loop instead of foreach loop
List<List<Integer>> list = new ArrayList<List<Integer>>();
for(int i=0;i<list.size();i++){
for(int j=0;j<list.get(i).size();j++){
do_something_on(list.get(i).get(j);
}
}
I'm facing a problem when operating on an ArrayList of ArrayList in Java. I have this thing in my code-
ArrayList<ArrayList<Integer>> L1 = new ArrayList<ArrayList<Integer>>();
Problem is, I have no idea as to how I should operate on this (addition, removal, traversal etc.). I wish to create an adjacency list (for implementing simple, undirected graphs), and my instructor suggests that I should create an ArrayList of ArrayList. I know I can do the following to add new element-
L1.add(//Something I want to add);
But this throws up an error in the current case for obvious reasons.
An ArrayList of an ArrayList, just think that the outer object is an ArrayList and you are done.
ArrayList<ArrayList<Integer>> list2d = new ArrayList<ArrayList<Integer>>();
// add an element to the list
list2d.add(new ArrayList<Integer>());
// retrieve a list
ArrayList<Integer> list1d = list2d.get(0);
// add an integer
list2d.get(0).add(123);
By the way, an adjacency list is just a list of edges, there's no need to store them for each vertex, especially if the graph is undirected. A list of Edge would be enough:
class Edge {
Vertex v1, v2;
}
ArrayList<Edge> adjacencyList;
If you want to store them on a per vertex basis then you could avoid using a list of lists by encapsulating the edges inside the vertex class itself but this will require twice the edges:
class Vertex {
int value;
ArrayList<Vertex> adjacency;
}
but which one is best depends on what kind of operation you need to perform on the graph. For a small graph there is no practical difference.
Another possible implementation, if you just need to know if two vertex are connected:
class Edge {
public final int v1, v2;
public boolean equals(Object o) { return o != null && o instanceof Edge && o.hashCode() == hashCode(); }
public int hashCode() { return v1 ^ v2; } // simple hash code, could be more sophisticated
}
Set<Edge> adjacencyList = new HashSet<Edge>();
Try L1.get(i).add(whatever);, and of course first check whether L1.get(i) exists, otherwise add that inner list first.
It's something like this:
List<List<Integer>> L1 = new ArrayList<List<Integer>>(); //better use interfaces
List<Integer> first = null;
if( L1.size() > 0) {
first = L1.get(0); //first element
}
else {
first = new ArrayList<Integer>();
L1.add(first);
}
first.add(4711); //or whatever you like to add
List<List<Integer>> L1 = new ArrayList<ArrayList<Integer>>();
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);
//add list to the list
L1.add(list1);
iterate over the list of lists
for( List<Integer> list: L1 ){
for(Integer i:list){
System.out.println(i);
}
}
You can only add objects of type ArrayList to L1. So you could do this:
ArrayList<ArrayList<Integer>> firstList = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> secondList = new ArrayList<Integer>();
secondList.add(0);
firstList.add(secondList);
L1.add(new ArrayList<Integer>());
will create a new List within the first list. Then you can
L1.get(0).add(5)
To add a new element to the outer array:
ArrayList<Integer> inner = new ArrayList<Integer>();
L1.add(inner);
Then to add element to the inner array:
int exampleInt = 10;
ArrayList<Integer> inner = L1.get(0);
inner.add(exampleInt);
To traverse all elements in all arrays:
for (ArrayList<Integer> inner : L1)
{
for (Integer element : inner)
{
System.out.println(element);
}
}