how to achieve this in java ? requirement given below - java

I want to create a list of list
List<integer> nodes[10]=new ArrayList();
i want this, coz i will be iterating through it and reading data..and it will be dynamically created in runtime depending upon the size of inputs

Creating an array of List seems a little weird to me, not that you can't do it, it just seems counter intuitive to me...
Instead, I'd create a List of Lists, something like...
List<List<Integer>> nodes = new ArrayList<List<Integer>>(10);
You would then just need to populate them with actually values, this will depend on what you are doing, but something like...
nodes.add(new ArrayList<Integer>(10));
When you need to access a particular list/node, you would just access it like any normal List
List<Integer> listOfIntegers = nodes.get(0);
Take a look at the Collections tutorial and List JavaDocs and ArrayList JavaDocs for more details.

An array of ArrayLists
List<Integer>[] nodes = new ArrayList[count];
An ArrayList of ArrayLists
List<List<Integer>> nodes = new ArrayList<List<Integer>>(count);

Related

Java equivalent of Python List

In Python there is a data structure called 'List'. By using 'List' data structure in Python we can append, extend, insert, remove, pop, index, count, sort, reverse.
Is there any similar data structure in Java where we can get all that function like Python List?
The closest Java has to a Python List is the ArrayList<> and can be declared as such
//Declaring an ArrayList
ArrayList<String> stringArrayList = new ArrayList<String>();
//add to the end of the list
stringArrayList.add("foo");
//add to the beggining of the list
stringArrayList.add(0, "food");
//remove an element at a spesific index
stringArrayList.remove(4);
//get the size of the list
stringArrayList.size();
//clear the whole list
stringArrayList.clear();
//copy to a new ArrayList
ArrayList<String> myNewArrayList = new ArrayList<>(oldArrayList);
//to reverse
Collections.reverse(stringArrayList);
//something that could work as "pop" could be
stringArrayList.remove(stringArrayList.size() - 1);
Java offers a great selection of Collections, you can have a look at a tutorial that Oracle has on their site here https://docs.oracle.com/javase/tutorial/collections/
IMPORTANT: Unlike in Python, in Java you must declare the data type that your list will be using when you instatiate it.
Several collections exist, but your probably looking for ArrayList
In Python you can simply declare a list like so:
myList = []
and begin using it.
In Java, it better to declare from the interface first so:
List<String> myList = new ArrayList<String>();
Python Java
append add
Remove remove
len(listname) list.size
Sorting a List can require a little more work, for example, depending on the objects you may need to implement Compactor or Comparable.
ArrayList will grow as you add items, no need to extend it on your own.
As for reverse() and pop(), I'll refer you can refer to:
How to reverse a list in Java?
How to pop items from a collection in Java?
Java has an interface called list, which has implementations such as ArrayList, AbstractList, AttributeList, etc.
https://docs.oracle.com/javase/8/docs/api/java/util/List.html
However, each one has different functionalities, and I don't know if they have everything you've specified such as .reverse().
Take a look at Collections in java. There are many lists (ArrayList, LinkedList etc). Choose the best datastructure needed for the requirement and complexity (both space and time).

How to combine array with arraylist in Java?

I need a 5-dimensional data structure in Java with "double" as type for all the cells. For 3 of dimensions I know the size, so it fits to array category. But for 2 of dimensions I don't know the size beforehand; looks like ArrayList.
I have been able to manage the combination for 3 dimensions in the past:
ArrayList(Double)[][] prXifY = (ArrayList(Double)[][]) new ArrayList[m][n];
But despite long hours working on it (and through search in the net), I wasn't able to scale it. I need something like this:
ArrayList(ArrayList(Double))[][][] prXiXjY = (ArrayList(ArrayList(Double))[][][]) new ArrayList(ArrayList<Double))[m][m][n];
When I tried the above code, it says:
"Cannot create a generic array of ArrayList(ArrayList(Double))"
I will appreciate quick and complete answers.
By the way, this is my very first post ever. I tried my best to do a good job on searching beforehand and explaining the problem clearly. Comments on these matters are appreciated as well. :)
An ArrayList is an object, and instantiated differently than an array is. In general, to say that you want an ArrayList that holds doubles, you might use something like:
ArrayList<Double> list = new ArrayList<Double>();
to specify that you have an ArrayList which holsts ArrayLists which hold doubles...
ArrayList<ArrayList<Double>> list = new ArrayList<ArrayList<Double>>();
You see where this is going, I hope.
This just creates the top-level list - it doesn't create any of the cells themselves. For that, you'll need additional new statements. This is going to get messy fast, and you may want to stop and consider if there is a better way to store the data than in a 5-dimension array.
I think what you want would look something like this
List<List<List<List<List<Double>>>>> myList= new ArrayList<List<List<List<List<Double>>>>> ();
as you can tell this looks insane and will be very hard to maintain. You should probably look at alternative methods of doing this.
Multi dimensional arrays can be created like so:
ArrayList<Double> oneDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<Double>> twoDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<ArrayList<Double>>> threeDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<ArrayList<ArrayList<Double>>>> fourDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<Double>>>>> fiveDimensionalArrayList = new ArrayList<>();
But I would definitely recommend considering whether a 5 dimensional array is what you require for the problem at hand; it smells like something is wrong

List of list iteration in code below -- which is better approach?

I am iterating over a List of Lists. In my code listofuserdetailsperAccount is List<List>. I am considering the two methods below, please let me know which way is correct, more efficient and should be followed in java coding.
Way 1-----
for(int i=0;i<=listofuserdetailsperAccount.size();i++){
List list=(List) listofuserdetailsperAccount.get(0);
}
Way 2---
for(int i=0;i<=listofuserdetailsperAccount.size();i++){
List list= new ArrayList();
list=(List) listofuserdetailsperAccount.get(0);
}
I'll go with for each loop
for( List userDetailsPerAccount : listOfUserDetailsPerAccount ) {
//anything you want to do with userDetailsPerAccount
}
Way 1 is better approach than Way 2. In Way 2 List list= new ArrayList(); it will create a extra ArrayList object which does not have any use, which will cause memory consumption for sometime.
And it is also recommended use type specific List<E> so that you dont cast at runtime it will be typesafe.
for(List<E> list : listOfUserDetailsPerAccount){
...
}
In Java 5 and above use for-each.
You have a couple of problems here, with both proposed solutions.
Your List<List> listofuserdetailsperAccount object is not properly typed, as the inner List is a raw type, something to be avoided. Assuming your inner list holds UserDetail objects, your list of lists should be of type List<List<UserDetail>>.
You don't use the for-each loop syntax to iterate over a List, which is Iterable.
for(List<UserDetail> innerList : listofuserdetailsperAccount)
In Way 2 you initialize List to a new ArrayList (which is a raw type, it should be new ArrayList<>() if you needed this) and then promptly overwrite this value with the contents of your outer list. This means you ask Java to construct a new object that is then immediately cleaned up by the garbage collector, unused. This is wasteful and unnecessary.
In summary, you likely want to do:
List<List<UserDetail>> listofuserdetailsperAccount = // initialize your list
for(List<userDetail> innerList : listofuserdetailsperAccount) {
// do work with your innerList now
}
You commented (tidied up):
So while initializing I am doing something like this now, can you please let me know if this is correct:
List<List<String>> listofAccountdetailsLoggedinUser = null;
listofAccountdetailsLoggedinUser = new ArrayList<List<String>>();
OR I should not put it as null and directly create an object like this:
List<List<String>> listofAccountdetailsLoggedinUser =
new ArrayList<List<String>>();
That is the right track, but you do not need to initialize the variable to null. It doesn't hurt anything, since it doesn't construct an unnecessary object, but there's no reason to - you can declare and initialize the variable in one line, like you do in your second example.
Additionally, you don't need to specify the type of the ArrayList on the right hand side, simply use the diamond operator <>, like so:
List<List<String>> listofAccountdetailsLoggedinUser = new ArrayList<>();
Also, consider a shorter variable name, there's no need to use such a long one, and it's no fun to type :)

How to add elements in List when used Arrays.asList()

We cannot perform <Collection>.add or <Collection>.addAll operation on collections we have obtained from Arrays.asList .. only remove operation is permitted.
So What if I come across a scenario where I require to add new Element in List without deleting previous elements in List?. How can I achieve this?
Create a new ArrayList using the constructor:
List<String> list = new ArrayList<String>(Arrays.asList("a", "b"));
One way is to construct a new ArrayList:
List<T> list = new ArrayList<T>(Arrays.asList(...));
Having done that, you can modify list as you please.
Arrays.asList(),generates a list which is actually backed by an array and it is an array which is morphed as a list. You can use it as a list but you can't do certain operations on it such as adding new elements. So the best option is to pass it to a constructor of another list obj like this:
List<T> list = new ArrayList<T>(Arrays.asList(...));
You can get around the intermediate ArrayList with Java8 streams:
Integer[] array = {1, 2, 3};
List<Integer> list = Streams.concat(Arrays.stream(array),
Stream.of(4)).collect(Collectors.toList());
This should be pretty efficient as it can just iterate over the array and also pre-allocate the target list. It may or may not be better for large arrays. As always, if it matters you have to measure.
The Constructor for a Collection, such as the ArrayList, in the following example, will take the array as a list and construct a new instance with the elements of that list.
List<T> list = new ArrayList<T>(Arrays.asList(...));
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList(java.util.Collection)
These days the streams API can easily get you an ArrayList in a concise and functional manner:
Stream.of("str1", "str2").collect(Collectors.toList()));
Of course this also has the flexibility to transform using mappings. For example, while writing unit tests for Spring security code it was convenient to write the following:
Stream.of("ROLE_1", "ROLE_2").map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
The list returned by Collectors.toList is an ArrayList and may be modified as required by your code.
Arrays.asList()
generates an unmodifiable list on object creation. You can use the below code.
List list = Collections.synchronizedList(new ArrayList(...));
This convert allows the list to add and remove objects. I have only tested in java 8.
ArrayList<Object> MyObjectList = new ArrayList<>();
Arrays.asList(params[1]).forEach((item)-> {
MyObjectList.add(item);
});

Creating a list from size

I know this is easy and can be done with 2 lines of code, but i am curious to know if there exists any such function
i have a int which tell me the size of list and i need to create a list say
List<Integer> intList;
i can create this by easily iterating through the size something like
for(int i=1 ; i <= size; i++) // started with 1 as i want it from 1
{
fill list
}
but i was just thinking as if there exists any such methods either in Collection API or Apache common
where i can pass the size to get a List with given size
Edit
May i was not able to put question in proper way, i want to get filled my list say
if size=4 than i was thinking abt something
Integer=1
Integer=2
Integer=3
Integer=4
and not an empty list with size 4
i know question do not make much sense, but still its better to clear your questions
Short answer: No
The two-liner you're currently using is already optimal.
The thing here is that List is an interface class and you can't create instances of an interface class. So before you want to construct it you need to know what kind of List you want to create. For the moment let's assume you want an ArrayList. From this moment on you can simply use the correct constructor to initialize your list e.g.
List<Integer> intList = new ArrayList<Integer>(10);
Which constructs an ArrayList of initial capacity 10.
For other kinds of list you can check the Java documentation.
To fill the list with initial data you can do something like this:
int[] myArray = new int[]{ 58,63,67,72,70,63,62,63 };
List<Integer> intList = new ArrayList<Integer>(myArray );
To answer the question after what you've added with your edit: No, there's no such method to fill a list with ascending integers in the standard collections API. You'll have to program a loop yourself and add elements to the list.

Categories