When I input a certain data item (character here), I can access the elements it relates to like:
When I input 'A', it gives me access to the values (2, 3, 4, 5), e.g.:
A - 2,3,4,5
B - 6,7,9
C - 10, 11, 12, 13
D - 1,8
and so on...
Also that A, B, C, D could be any data item, int or even a string.
What I am thinking is, I can hold on a linear array and then each item in the array be the header for a linked list. Is this a correct and optimal solution to the above data structure required? Do we already have some data structure to do this?
The best solution is to use a Hash Table with an array (or list) in the table value.
Here an example in Java using HashMap
Map<String,Integer[]> theMap;
theMap = new HashMap<String,Integer[]>();
theMap.put("A",{2,3,4,5});
theMap.put("B",{6,7,9});
theMap.put("C",{10,11,12,13});
theMap.put("D",{1,8});
/* Access Values */
int two = theMap.get("A")[0];
You could also use ArrayList instead of arrays for your integers.
The code would become as follows:
ArrayList<Integer> listA = new ArrayList<Integer>();
listA.add(2);
listA.add(3);
listA.add(4);
listA.add(4);
ArrayList<Integer> listB = new ArrayList<String>();
listB.add(6);
listB.add(7);
listB.add(9);
ArrayList<Integer> listC = new ArrayList<Integer>();
listC.add(10);
listC.add(11);
listC.add(12);
listC.add(13);
ArrayList<Integer> listD = new ArrayList<Integer>();
listD.add(1);
listD.add(18);
Map<String,List<Integer>> theMap;
theMap = new HashMap<String,List<Integer>>();
theMap.put("A",listA);
theMap.put("B",listB);
theMap.put("C",listC);
theMap.put("D",listD);
/* Access Values */
int two = theMap.get("A").get(0);
Use a simple dictionary/map/associative array whose elements are lists (or sets). In Python, a collections.defaultdict can help here:
import collections
d = collections.defaultdict(list)
A,B,C,D = ['A', 8, 3.0, (1,2)]
d[A].extend([2, 3, 4])
d[A].append(5)
# d[A] is now [2,3,4,5]
Related
What I would like to achieve is to have a nested list (or array) with elements as lists (or arrays) consisting a pair of integers. This is to store some data and I would like to access those integers efficiently.
So I created a nested list in Java like this:
List combined = new ArrayList();
int x[] = new int[2];
List segl = Arrays.asList(x)
combined.addAll(segl);
the nested list will later be appended with more list like segl.
Now I want to return a element from combined. But with combined.get(0) the returned element data type is object instead of a list like segl, so I couldn't do anything with it (eg. return the single int element from segl. I have no idea how to change it to a list or array.
Based on the information you provided in the comments, you want to have 'List of Lists' where the second List has two elements. Unfortunately you can't use arrays as the generic type of a List. So what I think that you want to do is probably this:
// This is a List which holds other Lists.
List<List<Integer>> combined = new ArrayList<>();
List<Integer seql = new ArrayList<>(2); // Initialize with a size of 2.
// add justs adds seql to combined. addAll will add all elements of seql to combines
combined.add(segl);
This makes it so that combined.get(0) returns a List<Integer>.
If you are using an array you have two options:
// Using Arrays.asList(..)
List<List<Integer>> combined = new ArrayList<>();
Integer[] seql = new Integer[2];
combined.add(Arrays.asList(segl));
//If Integer[] is not possible.
List<List<Integer>> combined = new ArrayList<>();
int[] seql = new int[2];
List<Integer> seqlAsList = Arrays.stream(seql).boxed().collect(Collectors.toList());
combined.add(seqlAsList );
I have values that I'd like to add into an ArrayList to keep track of what numbers have shown up.
The values are integers so I created an ArrayList;
ArrayList<Integer[]> list = new ArrayList<>();
int x = 5
list.add(x);
But I'm unable to add anything to the ArrayList using this method.
It works if I use Strings for the array list. Would I have to make it a String array and then somehow convert the array to integers?
EDIT: I have another question. I'd like the list to only hold 3 values. How would I do so?
List of Integer.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
You are trying to add an integer into an ArrayList that takes an array of integers Integer[]. It should be
ArrayList<Integer> list = new ArrayList<>();
or better
List<Integer> list = new ArrayList<>();
you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.
so if you want your code to work just put.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work
Actually what u did is also not wrong your declaration is right . With your declaration JVM will create a ArrayList of integer arrays i.e each entry in arraylist correspond to an integer array hence your add function should pass a integer array as a parameter.
For Ex:
list.add(new Integer[3]);
In this way first entry of ArrayList is an integer array which can hold at max 3 values.
The [] makes no sense in the moment of making an ArrayList of Integers because I imagine you just want to add Integer values.
Just use
List<Integer> list = new ArrayList<>();
to create the ArrayList and it will work.
Here there are two different concepts that are merged togather in your question.
First : Add Integer array into List. Code is as follows.
List<Integer[]> list = new ArrayList<>();
Integer[] intArray1 = new Integer[] {2, 4};
Integer[] intArray2 = new Integer[] {2, 5};
Integer[] intArray3 = new Integer[] {3, 3};
Collections.addAll(list, intArray1, intArray2, intArray3);
Second : Add integer value in list.
List<Integer> list = new ArrayList<>();
int x = 5
list.add(x);
How about creating an ArrayList of a set amount of Integers?
The below method returns an ArrayList of a set amount of Integers.
public static ArrayList<Integer> createRandomList(int sizeParameter)
{
// An ArrayList that method returns
ArrayList<Integer> setIntegerList = new ArrayList<Integer>(sizeParameter);
// Random Object helper
Random randomHelper = new Random();
for (int x = 0; x < sizeParameter; x++)
{
setIntegerList.add(randomHelper.nextInt());
} // End of the for loop
return setIntegerList;
}
I have an hash map, which maps integers to array of ArrayLists. For example, my data structure is the following:
7->((7,5,**4,3,1**),(7,6,4,3,1))
4->((4,2,1),(4,3,1))
Here, 7 is key, and arraylist e.g is (7,5,4,3,1), the array of arraylist in turn is ((7,5,4,3,1),(7,6,4,3,1))
4 is key, and arraylist e.g. is (4,2,1), the array of arraylist in turn is ((4,2,1),(4,3,1))
I wish to substitute the key values (in any given arraylist) and the values following it to create other arraylists, one example of this is given below:
7->((7,5,**4,2,1**),(7,6,4,2,1),(7,5,4,3,1),(7,6,4,3,1))
the thing I am not getting is how to obtain this substitution....to create bigger arraylists
the thing I am not getting is how to obtain this substitution....to create bigger arraylists..i know the datastructure..but want to create arraylists by substitution as given in subsequent example
Is there someway in java programming by which I may achieve this?
I am a novice at Java programming...I thought long about this but could not move it...can someone please help
HashMap<Integer,ArrayList<ArrayList<Integer>>> map;
map = new HashMap<Integer,ArrayList<ArrayList<Integer>>>();
EDIT: I've used 2 lines so that my answer could be more readable.
What actually do you want?
Is bellow code helpful?
Map<Integer, List<List<Integer>>> mapData = new HashMap<Integer, List<List<Integer>>>();
public void fillData(List<List<Integer>> lists)
{
// provide any kind of list of list
// e.g lists = {2,3,5,3}, {4,5,3,2}, {2,4,3}, {6,3,4}
for(List<Integer> list : lists)
{
int mapKey = list.get(0);
if(mapData.get(mapKey) == null)
{
// list of list will be null in first occurence of key(first element of list).
// create list of list and put tat in map.
List<List<Integer>> tempListOfList = new ArrayList<List<Integer>>();
tempListOfList.add(list);
mapData.put(mapKey, tempListOfList);
}
else
{
// from second occurence of same key.
// put list in the list of list of that key.
List<List<Integer>> listOfListInMap = mapData.get(mapKey);
listOfListInMap.add(list);
}
}
}
public List<List<Integer>> getListsByKey(int key)
{
// get list of list by mapKey
return mapData.get(key);
}
HashMap<Integer, ArrayList<ArrayList<Integer>>>.
below should do it:
Map<Integer, ArrayList <ArrayList<Integer>>> map = new hashMap<>();
Consider using a List of Lists and store this as part of a Map data structure. One possible way would be as follows:
Map<Integer,List<List<Integer>>> map = new HashMap<Integer, List<List<Integer>>>();
//How to add
List<List<Integer>> list = map.get(your_key);
if(list == null){ //This should be for the first time you're accessing the map with the key
list = new ArrayList<List<Integer>>();
}
//Create a inner list which will store the list of numbers
ArrayList<Integer> innerList = new ArrayList<Integer>();
innerList.add(integer_values);
//Add inner list to the list of lists
list.add(innerList);
//Finally put the list of list into the map with the key
map.put(your_key, list);
Edit: Assuming you know index of the list where you want to add new elements:
//Adding numbers to the inner list - assume you know the index
List<List<Integer>> list = map.get(key);
if(list == null || list.size() >= index){ //There's no list against the key or the size of the list is less then the index requested
return;
}
//Add new elements to the inner list
List<Integer> innerList = list.get(index);
innerList.add(your_new_int_values);
//Add inner list to the list of lists
list.add(innerList);
//Finally put the list of list into the map with the key
map.put(key, list);
You want to map integers to a list of lists of integers. This can be declared as:
Map<Integer, List<List<Integer>>> map = new HashMap<List<List<Integer>>>();
You can then put instances of ArrayList<List<Integer>> (or any other class that implements List) and for each such list of lists, you can add instances of ArrayList<Integer>.
You can then use the List.subList() method to put selected sublists into other entries in the map.
Say you have a list containing the two lists (7,5,4,3,1) and (7,6,4,3,1) stored under 7 and you want to construct the list of lists that should be stored under the key 4. You can do this:
List<List<Integer>> sevens = map.get(7);
List<List<Integer>> fours = new ArrayList<List<Integer>>();
for (List<Integer> aSevenList : sevens) {
int index = aSevenList.indexOf(4);
if (index >= 0) {
fours.add(aSevenList.subList(index, aSevenList.size()));
}
}
map.put(4, fours);
If you want to substitute one list as part of another, the following code fragment shows how that might be done:
int[] vals = { 7, 6, 5, 4, 3, 2, 1 };
List<Integer> list = new ArrayList<Integer>();
for (int val : vals) list.add(val);
List<Integer> sub = new ArrayList<Integer>();
sub.add(40);
sub.add(30);
sub.add(20);
System.out.println("Original list: " + list);
List<Integer> slice = list.subList(3, vals.length - 1);
slice.clear();
slice.addAll(sub);
System.out.println("Modified list: " + list);
This will generate the following output:
Original list: [7, 6, 5, 4, 3, 2, 1]
Modified list: [7, 6, 5, 40, 30, 20, 1]
Note that changes to a sublist are propagated to the original list.
i have two arraylist one have employee entity list other also have same entity list.
one Arraylist have all employees and other one have selected employees.
now i want to arrange employee in list in first Arraylist as on selected employees first arrive which is in second arraylist.
for Ex::
list1 [{1,test1}{2,test2},{3,test3},{4,test4}]
list2[{2,test2}{4,test4}]
what i want is
list1[{2,test2}{4,test4}{1,test1}{3,test3}]
How can i do this same by using single method or minimal line code ..
From what you have said it seems like you just need to take the members of list1 that are not in list2 and append them to list2 in the order they appear in list1.
Something like:
for ( Employee e : list1 ) {
if ( !list2.contains(e) ) {
list2.append(e);
}
}
Why not use Collections.sort(list1, yourComparator) where yourComparator sorts the entries in list1 as you need?
You could use Apache CollectionUtils like this:
CollectionUtils.addAll(list2, CollectionUtils.subtract(list1, list2));
You don't even need a loop or a comparator. Just use the Collections API!
Firstly, you want a LinkedHashSet - preserves uniqueness and order
Use the API to add list2, then list2, then populate a list with the set:
Here's an example using Integers:
// Set up your data
List<Integer> l1 = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
List<Integer> l2 = new ArrayList<Integer>(Arrays.asList(2, 5));
// Here's the 3 lines that do the work
Set<Integer> set = new LinkedHashSet<Integer>(l2);
set.addAll(l1);
List<Integer> l3 = new ArrayList<Integer>(set);
// All done
System.out.println(l3); // "[2, 5, 1, 3, 4]"
Using the examples below the 2nd part I see how to add values to a single dim array. But the 2 dim array I dont yet understand. In the 1st example the 1,2,3 I need to get from a database. The DB part I have figured out but how to put in the values I dont know.
If I was using an array it would be
myarray[row][column] = value;
so how do I do this with the List?
mylist.add --- something?
List<double []> // creates a list that stores arrays of doubles.
List<double []> myList = new ArrayList<Double>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});
List<Double> myList = new ArrayList<Double>();
myList.add(1);
myList.add(2);
myList.add(3);
You should avoid using arrays as generic type parameters as you can easily end up with "unchecked" warnings. Use collections (typically ArrayList) instead.
So instead of this:
List<double []> // creates a list that stores arrays of doubles.
List<double []> myList = new ArrayList<Double>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});
Do something like this:
List<List<Double>> myList = new ArrayList<List<Double>>();
myList.add(new ArrayList<Double>());
myList.add(new ArrayList<Double>());
myList.get(0).add(1);
myList.get(0).add(2);
myList.get(0).add(3);
Or to initialize together, you'd probably do something like:
List<List<Double>> myList = new ArrayList<List<Double>>();
List<Double> nested;
nested = new ArrayList<Double>();
nested.add(1);
nested.add(2);
nested.add(3);
myList.add(nested);
nested = new ArrayList<Double>();
nested.add(4);
nested.add(5);
nested.add(6);
myList.add(nested);
(You can add nested to myList before or after adding the elements to nested -- either way works so do whatever is clearer to you.)
To retrieve a specific element:
double value = myList.get(x).get(y);
To set a specific element:
myList.get(x).set(y, value);
This assumes that the list are already the right size, and that you just want to change the value of an existing element. (In other words, just like set behaves on a simple List.)
If you're talking about just doing inline initialization of a multidimensional array, I'm pretty sure you just use subsetted braces, like so:
Double array2D[][] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Do you want a collection-based solution for two-dimensional arrays? If so, then you're looking for a list of lists.
//Declaration
List<List<double[]>> twoDimList = new ArrayList<List<double>>();
//Adding values
twoDimList.add(new ArrayList<double>(1));
twoDimList.add(new ArrayList<double>(2));
twoDimList.add(new ArrayList<double>(3));
//Retrieving values
double value = twoDimList.get(1).get(1); //returns 1
List<T> myList = new ArrayList<T>();
T should be same. If T is double[] then it should be new ArrayList<double[]>()
then get(index) which is double array and get(index)[j] which is value. same logic with
d[i][j] = get(index)[j]
List<double []> myList = new ArrayList<double[]>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});
System.out.println(myList.get(0)[1]);