Insert at a specific position List<List<Map<Integer,Integer>>> - java

I'm new to Java. I need a way to insert value to Map in List<List<Map<Integer,Integer>>> at a specyfic position. Any ideas how to do it?
E.g. i need to work on my list like on 2d array, so for instance I need to insert value at tab[0][0] = value. I need similar operation on List<List<Map<Integer,Integer>>>

Access by index on lists is done via List.get(int). So, write:
tab.get(0).set(0, newMap);
Of course, your lists must be correctly initialised to the appropriate sizes for get(int) and set(int) to work

You are trying to convert nested list into array or you want to map values to array. Here is a small snippet how to achieve it.
List<List<Map<Integer, Integer>> list = new ArrayList<List<Map<Integer, Integer>>();
for(int i = 0; i<array.length; i++){
for(int j=0;j<array[i].length;j++){
array[i][j] = list.get(i).get(j);
/*
list.get(i) retrieves the i row
.get(j) retrieves the column
*/
}
}

Related

Is there a way to put all the values of a HashMap in an array?

I have a HashMap, let's say, with entries {1=1, 3=2, 4=1, 5=1, 6=1} . I'd like to be able to create an array just containing [1,2,1,1,1]. Is that possible?
To give some context, I'm trying to get something I can iterate over using an index, and anything like an array or ArrayList would work (the order of the items does matter).
I tried assigning the values to an array using
for (int j=0; j< frequencies.size(); j++){
for (int i : frequencies.values()) {
arr[j] = i;
}
}
frequencies.values() (frequencies is the name of my HashMap) wasn't of particular use, and I tried both iterating over that (didn't work) and assigning it to Collections wasn't useful. I tried assigning myHashMap.values() to an ArrayList as well, which obviously didn't work.
What would you recommend?
The type of frequencies.values() is a generic Collection, not necessarily an ArrayList. As a result, to convert it to an ArrayList, you must copy it -- fortunately, ArrayList has a constructor that accepts a generic Collection and copies it. As a result, all you have to do is write new ArrayList<>(frequencies.values()).
Is there a way to put all the values of a HashMap in an array?
Since you did specify an array as the target you can do it like this.
Map<Integer,Integer> map = new HashMap<>(Map.of(1,1,3,2,4,1,5,1,6,1));
int[] vals = map.values().stream().mapToInt(Integer::valueOf).toArray();
System.out.println(Arrays.toString(vals));
Prints
[1, 2, 1, 1, 1]
This is a kinda hacky way but it works well for me.... it assumes the values of the numbers from your hashmap are Longs.
Collect the values from your "frequencies" hashmap:
1. Collection<Long> values_from_hashmap = frequencies.values();
Create an array list from the collection of values:
2. ArrayList<Long> listOfValues = new ArrayList<Long>(values_from_hashmap);
Boom your listOfValues array list will contain the values from the orig hashmap

Java: Get all first entries from ArrayList

I have an ArrayList (~900 entries) containing arrays of user information:
[swaschit, Sophia Waschitz, Dormant, Inactive, 1/1/2018]
[kolanday, Kyle Olanday, Dormant, Inactive, 1/1/2018]
[npowers, Neil Powers, Assigned, Active, 2/11/2018]
I want to generate an array from this list containing only the first elements of each object:
[swaschit, kolanday, npowers, ...]
What is the most efficient way of doing this?
One way is to use a Stream and map each of the inner arrays to its first element:
List<String> firstElements = yourList.stream()
.map(x -> x[0].toString()) // you might need toString() here if your array is an Object[]
.collect(Collectors.toList());
If you would like an array of strings instead:
String[] firstElements = yourList.stream()
.map(x -> x[0].toString()) // you might need toString() here if your array is an Object[]
.toArray(String[]::new);
I also suggest you to not use nested arrays like this. You should create a class with the properties you want to store and create a List of your class.
As I suppose the first entry is unique (as it seems to be a username), I would suggest using a Map. That way, you could simply list the keys.
HashMap<String,ArrayList<String>> hashmap=new HashMap<>();
Alternatively, you could simply create a class containing that information, to avoid needing the use of an ArrayList, but I don't know if this is an option.
As pointed out using an appropriately designed Object rather than an array of such heterogeneous data (guessing they are Strings in reality).
If you insist on keeping it the way you have though, you just need to allocate a new array with the size of the original ArrayList and iterate through, fetching the desired column. Assuming ArrayList<String[]> list
int size = list.size();
String[] firstColumn = new String[size];
for (int i = 0; i < list.size(); i++) {
firstColumn[i] = list.get(i)[0];
}
I suppose that you can do
list.stream().map(array -> array[0].toString()).toArray()

Most efficient way of combining two big lists

I have two lists that each contain 2500 values.
List<String> headers = new ArrayList<String>();
List<String> data = new ArrayList<String>();
I need to combine these two lists into a two dimensional list or any other appropriate data structure that allows me to only iterate through once rather than doing the operation below which is very slow when dealing with big lists:
for (int i = 0; i < headers.size(); i++) {
for (int in = 0; in < data.size(); in++) {
}
}
It's critical the index of each list match each other when combining these two lists. So headers.get(9); must match data.get(9);.
I need a new list or other data structure that will allow me to store each value in the two lists as pairs. So headers.get(0); would be paired with data.get(0);.
Any help would be appreciated.
About
It's critical the index of each list match each other when combining these two lists.
Create a simple class to hold both value
class MyData{
String header;
String data;
}
Then use a single List<MyData>. You will only have one List of 2500 items.
Based on what you do with those data, other collection could be more efficient to read, but not to update.
Make a new class:
class HeadersWithData{
String header;
String data;
HeadersWithData(String header, String data){
this.header = header;
this.data = data;
}
}
Declare your list:
List<HeadersWithData> combinedList = new ArrayList<>();
And fill the list:
for (int i = 0; i < headers.size(); i++){
combinedList.add(new HeadersWithData(headers.get(i), data.get(i)));
}
Note: This is a one-dimensional list. A two-dimensional list would not make any sense in your case.
If you need the one list to contain the same pairs that you'd get doing the nested loop, there's nothing you can do. You're iterating over 2500*2500=6250000 pairs. Nothing will make that fast. Iterating over one list instead of the nested for loops will not make a difference.
If you don't want to iterate over every combination of elements from both lists, but iterate over one list once and then iterate over the other list once, then that's equivalent to doing one for loop after the other, not one for loop inside of the other. And that will be fast whether you combine them into one big list, or iterate over one list and then the other.
I'm not really sure if the loop you presented is what what you really wanted to archieve, but if you wanted every element of the first list correspond to exactly one element of the second list I would suggest using Map<String, String>. This allows you to map every element of the first list of strings to one elements of the second list. Each pair is then stored as an Map.Entry<Key,Value>.
That way you are able to iterate only once through the map using for example loop like this:
for(Map.Entry<String,String> entry : map.entrySet()) {...}

How to make ArrayList that work as two dimentional array in java?

I want to make arrayList object in java that work as two dimentional array. My question is how can we access value from specific dimention from arrayList.
in two dimentional array, if i want to access value then it can be as m[i][j].
But in arraylist how can i do that ?
You mean something like a List in a List??
May be something like...
List<List<...>> twoDList = new ArrayList<>();
i want to make a List, in which each List key contains another List inside it
It should more like you want some kind of Map, which is basically a key/value pair.
Map<String, List<String>> mapValues = new HashMap<>(25);
List<String> listOfValues = ...;
//...
mapValues.put("A unique key for this list", listOfValues);
//...
List<String> thatListOfValues = mapValues.get("A unique key for this list");
List<List<Integer>> list = new ArrayList<List<Integer>>();
list.add(new ArrayList<Integer>());
list.add(new ArrayList<Integer>());
list.get(0).add(5);
list.get(1).add(6);
for(List<Integer> listiter : list)
{
for(Integer integer : listiter)
{
System.out.println("" + integer);
}
}
This way you can get the items like
list.get(1).get(0); //second dimension list -> integer
EDIT:
Although it is true that you can use a Map if you are trying to use numeric indices for example for each list, like so:
Map<Integer, List<YourObject>> map = new HashMap<Integer, List<YourObject>>();
map.put(0, new ArrayList<YourObject>());
map.put(5, new ArrayList<YourObject>());
map.get(0).add(new YourObject("Hello"));
map.get(5).add(new YourObject("World"));
for(Integer integer : map.keySet())
{
for(YourObject yourObject : map.get(integer))
{
yourObject.print(); //example method
System.out.println(" ");
}
}
Although even then the accessing of Lists would be the same as before,
map.get(0).get(1); //List -> value at index
Obviously you don't need to use Integers as the generic type parameter, that's just a placeholder type.
The solution like List<List<..>> is slow then you should use one dimention array like
// Two dimentions: m and n
List<String> arr = new ArrayList<String>(m*n);
for (int i=0; i< m; ++i) {
for (int j=0; j<n; ++j) {
String str=arr.get(i*n + j);
//You code here
}
}
Memory is an important consideration here.
It can be acceptable to model a 2D (or higher dimension) array using a 1D container. (This is how the VARIANT SAFEARRAY of Microsoft's COM works.) But, consider this carefully if the number of elements is large; especially if the container allocates a contiguous memory block. Using something like List<List<... will model a jagged-edged matrix and can fragment your memory.
With the 1D approach, you can use the get(index) method on the ArrayList appropriately transformed:
Given the (i)th row and (j)th column, transform using index = i * rows + j where rows is the number of rows in your matrix.
An arraylist is not an object to make a 2 dimentional arrays. However you can use it anyway :
You can use :
new ArrayList<ArrayList<Object>>; //or
new ArrayList<Object[]>;
But you should implement your own matrix class because you will probably have some check to do and a function get(int row, int column) would be cool
Also consider Table collection provided by Google Guava library. ArrayTable is an implementation based on 2D array.
You cane define like this
1>
List<Object[]> list = new ArrayList<Object[]>();
Fetching
list.get(i)[j];
2>
List<Map<Integer,Object>> list = new ArrayList<Map<Integer,Object>>();
Fetching
list.get(i).get(j);

Unable to get values from a hashmap which uses a arraylist as value is cleared

I am working on a piece of code which has a Hashmap. This hashmap has a string as key and an arraylist as value. I populate the arraylist and then put the value into the hashmap. After putting the value, I want to clear the arraylist so that no old values are present.
Please see below code:
ArrayList<Bean> elements = new ArrayList<Bean>();
for(int j=0; j<array.length; j++){
String[] id = {"2439","70212","9021","0104","0255","10353","3889","8990","10277"};
String[] Title = {"Gulliver","Good=Guys","Gnomeo","Gene","ABCD","High","Green=Lantern","Gnomeo2","WXYZ"};
for(int i=0; i<id.length; i++){
Bean bean = new bean();
bean.ID(id[i]);
bean.Title(title[i]);
elements.add(bean);
}
udbResults.put(array[j], elements);
elements.clear();
}
Now when i try to print the values from the hashmap, i am not getting any content. This maybe because of the arraylist.clear(). Why does this happen?
Also I didnt want to create new arraylist for each data hence i wanted to remvoe the contents but its not working.
Any way to go about this.
Thanks,
swati
what you r doing is simply createing and populating an arraylist, then you are puting a link to arraylist into hashmap...so now you have 2 links for one arraylist. One was called 'elements' another in hashmap. And then you r deleting all elements from your arraylist. Ofcause you will lose everething. So now you still has two links but to the empty arraylist

Categories

Resources