add data into an object list index by index - java

I have two lists of data with the same size.
I am adding the two lists to an array of objects but the Syllabus list is completely added to the object list before being added to the Article list. My challenge is add data to the Syllabus list and the Article list simultaneously.
For instance if the index of syllabus is zero, let it get the index of the Syllabus and of the Article and add it to the object list before moving
to the index of 1 till the last index so as the index of Syllabus grows so does the Article until they get to the last element in the list.
Below is my attempt but it's not working index by index
Here is the object list
#SuppressWarnings("unused")
List <Object> obj = new ArrayList<Object>();
List <Syllabus> syllabus = articleOfAssociationDao.findByType(type);
obj.addAll(syllabus); //adding to an object list
for(int i =0; i < syllabus.size(); i++) {
List<Article> articleContent = articleContentDao.findBySyllabus(syllabus.get(i));
obj.addAll( articleContent); //adding to an object list
}

Would the following work?
for(int i =0; i < syllabus.size(); i++) {
List<Article> articleContent = articleContentDao.findBySyllabus(syllabus.get(i));
obj.add(syllabus.get(i));
obj.addAll(articleContent);
}

Related

ArrayList of ArrayList of Integers

I have an ArrayList of ArrayLists of Integers. [ArrayList > list]. How do I set value foe an index of any inner ArrayList? I do not want to build an ArrayList of Integers and add them to the List of List using add function, but I want to set values to it, as I already have the List of List.
I'm assuming you have something like:
List<List<Integer>> list = new ArrayList<>(outerSize);
You've also said:
I do not want to build an ArrayList of Integers and add them to the List of List using add function, but I want to set values to it, as I already have the List of List.
If that's true, it means you've already done this or similar:
for (int i = 0; i < outerSize; ++i) {
List<Integer> inner = new ArrayList<>(innerSize);
for (int j = 0; i < innerSize; ++i) {
inner.add(defaultValue);
}
list.add(inner);
}
So given all of that, it's just get (to get the inner list from the outer list) and set (to set a value on it):
list.get(outerIndex).set(innerIndex, value);

Type mismatch when creating List of objects

I am trying to part the mainListarraylist to 3 sublist Arraylist and then add it as sublist in other arraylist mainSublist but I am getting this error:
How can I fix it?
I appreciate any help.
1)-Type mismatch: cannot convert from List to ArrayList
2) -The method add(RootCreator) in the type ArrayList is not applicable for the arguments (ArrayList)
Code:
ArrayList<RootCreator> mainList = new ArrayList<RootCreator>();
for (String key : names) {
RootCreator rootcreat = join_line(path, key);
mainList.add(rootcreat);
}
ArrayList<RootCreator> mainSublist = new ArrayList<RootCreator>();
for(int i= 0 ; i < mainList.size(); i++){
int index = i*3;
//the error 1 is here
ArrayList<RootCreator> sublist = mainList.subList(0, index);
//error 2 is here
mainSublist.add(sublist);
}
All List are not ArrayList, so when you use sublist you get a generic List. On the other hand, the method to add a collection to another collection is addAll instead add.
List<RootCreator> mainList = new ArrayList<RootCreator>();
for (String key : names) {
RootCreator rootcreat = join_line(path, key);
mainList.add(rootcreat);
}
List<RootCreator> mainSublist = new ArrayList<RootCreator>();
for(int i= 0 ; i < mainList.size(); i++){
int index = i*3;
//the error 1 is here
List<RootCreator> sublist = mainList.subList(0, index);
//error 2 is here
mainSublist.addAll(sublist);
}
The subList method returns a List, not an ArrayList, and you cannot assign a List to an ArrayList. In fact, the List returned by the subList method is not an ArrayList.
If it needs to be an ArrayList, then create an ArrayList out of the sub list.
ArrayList<RootCreator> sublist = new ArrayList<>(mainList.subList(0, index));
If you just need a List, then make sublist a List instead.
List<RootCreator> sublist = mainList.subList(0, index);
You can't add an ArrayList<RootCreator> to an ArrayList<RootCreator>; you must add a RootCreator. If you want to add the elements of sublist to another list, then use the addAll method.
mainSublist.addAll(sublist);
OK, let's look at the two errors here:
//the error 1 is here
ArrayList<RootCreator> sublist = mainList.subList(0, index);
This is telling you that you're trying to assign something of the type List to a variable that's declared as an ArrayList. While an ArrayList is a subtype of List, it doesn't work both ways - you can assign an ArrayList to a List, but not vice versa. So let's change your declaration:
//the error 1 was here, but fixed.
List<RootCreator> sublist = mainList.subList(0, index);
The second one is slightly different:
//error 2 is here
mainSublist.add(sublist);
Here, you've got a list defined to hold items of the type RootCreator - but you're not adding RootCreator items, you're adding a list of them. So if you want to have the list hold other lists, you need to specify that when you create it:
ArrayList<List<RootCreator>> mainSublist = new ArrayList<List<RootCreator>>();
But, if you're trying to just keep a single list and want to add everything from the sublists, then instead, change your code to:
//error 2 was here, but Fixed
mainSublist.addAll(sublist);

Convert List into List of Lists that contain 10 items

I have a List of pojos. To convert this List of pojos into a List of List where each sublist is of the size 10 or less. So for example a List of size 13 is converted to a two element List. The first element is a List of 10 items, the second element is a List 3 items.
So the data structure is List<List<pojo>>
To create this List of lists :
List<List<pojo>> pojoList
counter = 0;
initialise new tempList
iterate list
add current pojo to temp list
if counter = 10 then add tempList to pojoList
reset counter and tempList and continue until list is iterated
Is there an alternative solution ?
Consider Guava's Lists.partition().
Use sublist
List<Pojo> originalList.... //your list of POJOs
List<List<Pojo>> pojoList = new ArrayList<List<Pojo>>(originalList/10 + 1);
for(int i = 0; i < originalList.size(); i+=10){
if(i + 10 > originalList.size()){
pojoList.add(originalList.subList(i, originalList.size()));
}
else{
pojoList.add(originalList.subList(i, i + 10));
}
}
You can probably use subList.
You still need to iterate but you are not going to need to create the tempList

Retrieving elemnts from an ArrayList by specifying the indexes

Is there a method in Java to get the list of objects from an Arraylist to another ArrayList, by just specifying the start and end index?
Yes you can use the subList method:
List<...> list2 = list1.subList(startIndex, endIndex);
This returns a view on that part of the original list, it does not copy the data.
If you want a copy:
List<...> list2 = new ArrayList<...> (list1.subList(startIndex, endIndex));
/create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
/*
To get a sub list of Java ArrayList use
List subList(int startIndex, int endIndex) method.
This method returns an object of type List containing elements from
startIndex to endIndex - 1.
*/
List lst = arrayList.subList(1,3);
//display elements of sub list.
System.out.println("Sub list contains : ");
for(int i=0; i< lst.size() ; i++)
System.out.println(lst.get(i));

Add object to ArrayList at specified index

I think it's a fairly simple question, but I can't figure out how to do this properly.
I've got an empty arraylist:
ArrayList<object> list = new ArrayList<object>();
I've got some objects In which I want to add object and each object has to be at a certain position. It is necessary however that they can be added in each possible order. When I try this, it doesn't work and I get an IndexOutOfBoundsException:
list.add(1, object1)
list.add(3, object3)
list.add(2, object2)
What I have tried is filling the ArrayList with null and then doing the above. It works, but I think it's a horrible solution. Is there another way to do this?
You can do it like this:
list.add(1, object1)
list.add(2, object3)
list.add(2, object2)
After you add object2 to position 2, it will move object3 to position 3.
If you want object3 to be at position3 all the time I'd suggest you use a HashMap with position as key and object as a value.
You can use Array of objects and convert it to ArrayList-
Object[] array= new Object[10];
array[0]="1";
array[3]= "3";
array[2]="2";
array[7]="7";
List<Object> list= Arrays.asList(array);
ArrayList will be- [1, null, 2, 3, null, null, null, 7, null, null]
If that's the case then why don't you consider using a regular Array, initialize the capacity and put objects at the index you want.
Object[] list = new Object[10];
list[0] = object1;
list[2] = object3;
list[1] = object2;
You could also override ArrayList to insert nulls between your size and the element you want to add.
import java.util.ArrayList;
public class ArrayListAnySize<E> extends ArrayList<E>{
#Override
public void add(int index, E element){
if(index >= 0 && index <= size()){
super.add(index, element);
return;
}
int insertNulls = index - size();
for(int i = 0; i < insertNulls; i++){
super.add(null);
}
super.add(element);
}
}
Then you can add at any point in the ArrayList. For example, this main method:
public static void main(String[] args){
ArrayListAnySize<String> a = new ArrayListAnySize<>();
a.add("zero");
a.add("one");
a.add("two");
a.add(5,"five");
for(int i = 0; i < a.size(); i++){
System.out.println(i+": "+a.get(i));
}
}
yields this result from the console:
0: zero
1: one
2: two
3: null
4: null
5: five
I draw your attention to the ArrayList.add documentation, which says it throws IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
Check the size() of your list before you call list.add(1, object1)
You need to populate the empty indexes with nulls.
while (arraylist.size() < position)
{
arraylist.add(null);
}
arraylist.add(position, object);
#Maethortje
The problem here is java creates an empty list when you called new ArrayList and
while trying to add an element at specified position you got IndexOutOfBound ,
so the list should have some elements at their position.
Please try following
/*
Add an element to specified index of Java ArrayList Example
This Java Example shows how to add an element at specified index of java
ArrayList object using add method.
*/
import java.util.ArrayList;
public class AddElementToSpecifiedIndexArrayListExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
/*
To add an element at the specified index of ArrayList use
void add(int index, Object obj) method.
This method inserts the specified element at the specified index in the
ArrayList.
*/
arrayList.add(1,"INSERTED ELEMENT");
/*
Please note that add method DOES NOT overwrites the element previously
at the specified index in the list. It shifts the elements to right side
and increasing the list size by 1.
*/
System.out.println("ArrayList contains...");
//display elements of ArrayList
for(int index=0; index < arrayList.size(); index++)
System.out.println(arrayList.get(index));
}
}
/*
Output would be
ArrayList contains...
1
INSERTED ELEMENT
2
3
*/
How about this little while loop as a solution?
private ArrayList<Object> list = new ArrayList<Object>();
private void addObject(int i, Object object) {
while(list.size() < i) {
list.add(list.size(), null);
}
list.add(i, object);
}
....
addObject(1, object1)
addObject(3, object3)
addObject(2, object2)
This is a possible solution:
list.add(list.size(), new Object());
I think the solution from medopal is what you are looking for.
But just another alternative solution is to use a HashMap and use the key (Integer) to store positions.
This way you won't need to populate it with nulls etc initially, just stick the position and the object in the map as you go along. You can write a couple of lines at the end to convert it to a List if you need it that way.
Bit late but hopefully can still be useful to someone.
2 steps to adding items to a specific position in an ArrayList
add null items to a specific index in an ArrayList
Then set the positions as and when required.
list = new ArrayList();//Initialise the ArrayList
for (Integer i = 0; i < mItems.size(); i++) {
list.add(i, null); //"Add" all positions to null
}
// "Set" Items
list.set(position, SomeObject);
This way you don't have redundant items in the ArrayList i.e. if you were to add items such as,
list = new ArrayList(mItems.size());
list.add(position, SomeObject);
This would not overwrite existing items in the position merely, shifting existing ones to the right by one - so you have an ArrayList with twice as many indicies.
You should set instead of add to replace existing value at index.
list.add(1, object1)
list.add(2, object3)
list.set(2, object2)
List will contain [object1,object2]
Suppose you want to add an item at a position, then the list size must be more than the position.
add(2, item): this syntax means, move the old item at position 2 to next index and add the item at 2nd position.
If there is no item in 2nd position, then this will not work, It'll throw an exception.
That means if you want to add something in position 2,
your list size must be at least (2 + 1) =3, so the items are available at 0,1,2 Position.
in that way it is ensured that the position 2 is accessed safely and there would be no exception.
If you are using the Android flavor of Java, might I suggest using a SparseArray. It's a more memory efficient mapping of integers to objects and easier to iterate over than a Map

Categories

Resources