Best way to store data in array - java

I get from database some informations and I'd like to store it like:
Person[0] {name:"Marie", email:"marie#marie.com", adress:"address marie"}
Person[1] {name:"Josh", email:"josh#josh.com", adress:"address josh"}
...
So I can add more items, access items using position and after user show each position, remove it from array. eg: after user see array position 0 (Marie) info, remove array position 0 from memory.
What is the best way to do it? array, arraylist, arraymap...? How to declare, add and remove positions infos?
Thanks.

I guess you can use LinkedList may be, it provides constant O(1) time for adding item at last and removing first item.
You can use offer or add methods to add item and poll() to remove first item
You can do below operations
val list = LinkedList<String>()
list.add("Android") // add items to the end
list.add(5, "Hello") //adds item at mentioned position
list.poll() // removes first item
list.removeAt(4) //removes item at certain position
list.pollLast() // removes last item

To achieve what you are expecting, you could do something like this:
List<Map<String,String>> data = new ArrayList();
Map<String,String> map = new HashMap();
map.put("name","Marie");
map.put("email","marie#marie.com");
map.put("adress","address marie");
data.add(map);
System.out.println(data.get(0));
For inserting multiple items:
List<Map<String,String>> data = new ArrayList();
Map<String,String> map = new HashMap();
for(Class a : object)
{
map.put("name",a.name); //a.name is just from my imagination only. use your own aproach to get name.
map.put("email",a.email);
map.put("address",a.address);
data.add(map);
}
System.out.println(data.get(0));

Use ArrayList instead of Array for store data
String[] Person = {name:"Marie", email:"marie#marie.com", adress:"address marie"}
Person[1] {name:"Josh", email:"josh#josh.com", adress:"address josh"}
ArrayList<String> data = new ArrayList()<String>;
data.add(Person);

Related

Map object keeps getting overwritten when adding

I have a database call that will return a result set with city and states into a result set object called cityAndState. I am trying to loop through and put each city and state into a map and then add to an array list of maps.
So I have an array list with 50 city and state Maps with <key,values> of city and state. For instance [{city-Los Angeles, state=California},...] But each time I am overwriting the value.
Map<String,String> citiesAndStateCombinations = new HashMap<>();
List<Map<String,String> citiesStates = new ArrayList<>();
while(cityAndState.next()){
citiesStates.put("city", cityAndState.getString("city");
citiesStates.put("state", cityAndState.getString("state");
citiesAndStateCombinations.add(citiesStates);
}
Leaves an array with the last values printed 50 times.
[{city-Boise, state=Idaho}, {city=Boise, state=Idaho}.....50}
Each time it erases the previous value. I see why it is doing it, it's setting all the elements to the last value added which makes sense but is there a way to add the values so I am left with an array of the 50 cities and States?
The thing is you're implementing HashMap in the wrong way, or you misunderstood it: "A Map cannot contain duplicate keys and each key can map to at most one value."
What you're doing in the above code -
citiesStates.put("city", cityAndState.getString("city");
citiesStates.put("state", cityAndState.getString("state");
You're putting values with the same key "city" & "state" that's why it's overwriting the values.
The correct way to do this will be -
Map<String,String> citiesAndStateCombinations = new HashMap<>();
while(cityAndState.next()){
if(!citiesAndStateCombinations.containskey(cityAndState.getString("city"))){
citiesAndStateCombinations.put(cityAndState.getString("city"), cityAndState.getString("state"))
}
}
This will give you a city and state unique map now if you want it to be added to a list you can add this line at last but I don't see any use of it -
List<Map<String,String> citiesStates = new ArrayList<>();
citiesStates.add(citiesAndStateCombinations);
Please add this after closing the while loop.
----------EDITED----------
To achieve the solution which you're looking for you need to write something like this -
enter code here
while(----){
Map<String,String> citiesAndStateCombinations = new HashMap<>();
if(citiesAndStateCombinations.containsKey("city="+cityAndState.getString("city"))){
citiesAndStateCombinations.put(cityAndState.getString("city"), cityAndState.getString("state"))
citiesStates.add(citiesAndStateCombinations);
}
This will give you desired output -
[{city=XXXXXX=state=XXXXXX},
{city=XXXXXX=state=XXXXXX},
{city=XXXXXX=state=XXXXXX}]

How to add new items to a list of filled arraylist in java?

I have a book list as below
public static ArrayList<List<String>> booksList = new ArrayList<List<String>>();
And it is filled as shown below
booksList.add(Arrays.asList("Coders at Work", null));
booksList.add(Arrays.asList("Code Complete",null));
booksList.add(Arrays.asList("The Mythical Man Month",null));
booksList.add(Arrays.asList("Don't Make Me Think",null));
booksList.add(Arrays.asList("The Pragmatic Programmer",null));
I want to add items to list of specific row of Arraylist
booksList.get(0).add("BUYED");
booksList.get(0).add(0,"BUYED");
But it doesn't work. How to add more items? or Is there a better way to handle this situation?
You cannot add or remove elements of a List created by Arrays.asList().
Its javadoc states indeed :
Returns a fixed-size list backed by the specified array.
To be able to add new elements after the list was created, you could wrap the fixed size List in a new ArrayList.
For example this :
BooksList.add(Arrays.asList("Coders at Work", null));
could be written :
BooksList.add(new ArrayList<>(Arrays.asList("Coders at Work", null)));

Adding elements to List<List<String>> from an array list

I want to add COPIES of data to my List but when I use .add, it adds a reference and not a copy. I'll try to explain what I mean.
List<List<String>> formattedTempMatches = new ArrayList<>();
ArrayList<String> rowFormattedMatches = new ArrayList<>();
rowFormattedMatches.add(matchesArray[0]);
rowFormattedMatches.add(matchesArray[1]);
rowFormattedMatches.add(matchesArray[2]);
formattedTempMatches.add(rowFormattedMatches);
//rowFormattedMatches.clear();
rowFormattedMatches.add(matchesArray[3]);
rowFormattedMatches.add(matchesArray[4]);
rowFormattedMatches.add(matchesArray[5]);
formattedTempMatches.add(rowFormattedMatches);
I've written my code outside of a loop to try to explain myself better. I want to add 3 elements to an ArrayList (of which the elements come from a normal array) then add that ArrayList to a list of lists. When the ArrayList is added to the list, I want to clear it and refill it with 3 more elements and then add it to the next index of the List. The problem is once I clear it, the data is removed from the list. If I don't clear it, the list has 6 elements at each index when there's only supposed to be 3. What should I do?
Apologies for my possibly confusing explanation.
The call of clear() empties the list. As you are using the same instance for each iteration, this will not work. What you can do instead of clearing the list is create a new instance:
List<List<String>> formattedTempMatches = new ArrayList<>();
ArrayList<String> rowFormattedMatches = new ArrayList<>();
rowFormattedMatches.add(matchesArray[0]);
rowFormattedMatches.add(matchesArray[1]);
rowFormattedMatches.add(matchesArray[2]);
formattedTempMatches.add(rowFormattedMatches);
rowFormattedMatches = new ArrayList<>(); // new instance of an empty list
rowFormattedMatches.add(matchesArray[3]);
rowFormattedMatches.add(matchesArray[4]);
rowFormattedMatches.add(matchesArray[5]);
formattedTempMatches.add(rowFormattedMatches);

Add an element in arraylist of arraylist using index

I have a arrayList done this way:
ArrayList<ArrayList<Double>> level = new ArrayList<ArrayList<Double>>(levels + 1);
So something like:
enter image description here
What I would do is add a new element to the internal list saved in a certain index i of the external list.
How can I do this?
I can't use method arrayList.add(i, 0.0);.
Use index from the external ArrayList and use it to add the number. Like this
level.get(i).add(1.1);
You need to get the list at a given position first and then insert into it the value desired.
Example:
final List<List<Double>> listOnList = new ArrayList<List<Double>>();
listOnList.add(new ArrayList<Double>());
listOnList.get(0).add(155.0);

how to calculate efficent how many elements in a list are the same?

I need to do the following task:
I have a list with items.
Each of the items also have a List with strings like "gkejgueieriug"
Now I need to run throw the list and check how many of the items in the list of each item are also in the current element
here is a small pseudeo code:
OneItem;
List AllItems;
for Item in AllItems:
int count = number strings in Item.Values which are also in OneItem.Values
because the data is very big, I need some help to make a efficent implementation.
How to do this? Should I use a hashmap? how to count the overlap?
Your question doesn't provide detailed information about the involved types which you want to compare. So I assume you have a List<Item>. Each item has a String and an own List<Item>
So first I would create a HashSet of the Strings of the Items in your AllItems-List. Iterate the AllList and add the String of each Item to the HashSet.
Then in the second step iterate the AllList again and iterate the List in the Items and check each String here if it is in the HashSet which was created before.
If you have to check this several times you can keep the HashSet as a cache which you refresh when the AllList gets changed.
// Step 1: Create Set of Strings
Set<String> allStrings = new HashSet<String>();
for (Item item : allList) {
allStrings.add(item.getString());
}
// Step 2: Calculate occurrences
for (Item item : allList) {
for (Item internalItem : item.getItems()) {
if (allStrings.contains(internalItem.getString()) {
// Count one up for this String
// This might be done by replacing the HashSet by a HashMap and use its values for counting
}
}
}
Make Item.Values a Set rather than a List. A decent Set implementation - like a HashSet - will run the contains() operation in constant time. Then iterate over one set and increment a count each time the other set contains the element.
An optimization is to always iterate over the smaller set. That way the counting operation is O(n) where n is the size of the smaller set.
If the comparison is only one way (i.e. only counting strings in one list that are also in another but NOT the other way around) then the best way of doing it would probably be to put both lists in a Set instead:
HashSet firstSet = ...
HashSet secondSet = ...
for(each value in firstSet)
{
if(secondSet.contains(value)
{
// Do what you want with the value.
// Sugestion: Add value to a separate set
// so you can track duplicates etc
}
}
With this code you create an ArrayList of Map with the string values and the number of matches in your OneItem.Values...
ArrayList<Map<String,Integer>> matches=new ArrayList<>();
for (Item i : AllItems) {
Map<String,Integer> map=new HashMap<>();
for(String s:values){
map.put(s,Collections.frequency(OneItem.Values, s));
}
matches.add(map);
}

Categories

Resources