Removing multiple entries from ArrayList in Java by date - java

So I have the arrayList called inPeople, which has this class stored in it named peopleIn. This is the data stored in the class
peopleIn( int scannerNum, Date date, int empNum){
So basically, my program is a system which reads through the logs of a punch clock to find out who's in the building. The problem is, if the person punches in a number of times, but never punches out, i end up with duplicates in my list. So basically, I need to keep the most recent punch in.
Can this be done?

You can use Map<Key,Value>, If you put value for same key. previous value will be replace by current value.
Eg:
Map<String,String> map=new HashMap<>();
map.put("emp1", "val1");
map.put("emp2","val2");
System.out.println(map);
// now i am putting emp1, val3
map.put("emp1","val3");
System.out.println(map);
Out put:
{emp2=val2, emp1=val1}
{emp2=val2, emp1=val3}

You can store them in a Map, where the key is the employee number and the value is the date. This will prevent the duplicates.

Related

Java - HashMap for booking system

I have been given an exercise to develop an appropriate data structure to implement a tennis court booking system.
A hashmap is what is required for this and I was given a diagram as a visual representation of the data structure.
From looking at the diagram, I am unclear on how the Key and Value should be defined in the HashMap. Should 'Court' be a class, which is the Key?
For the value, it shows a time, and a players name. How would the value be defined, since it has two values of time and player name?
diagram link
Say we have a HashMap named as "Date1".
Well, now i can put a value with a key in this "Date1" HashMap & later can retrieve that value with the key -> Date1.get("key")
According to your diagram, the keys will be court1, court2, ....
So that, when i will ask for Date1.get("court1"), i can get this ArrayList
But, in this arraylist, each row consist of two values. If our list had one string values in each row, we could say that this is a arraylist of string type.
So lets make our own class (like a type) which can store two values (like "9:00", "player")
public class EntryInfo{
String time, player;
public EntryInfo(String time, String player) {
this.time = time;
this.player = player;
}
}
So if we create an object of "EntryInfo" class, that object will be able to store two values - and each row of our arraylist is of this type.
so, lets sum up :
our hashmap key will be "court1, court2..."
and each key will hold values of ArrayList<EntryInfo> type.
So our hashmap will be like HashMap< String, ArrayList<EntryInfo> >
Now, lets imagine the scenario according to your diagram.
first, lets talk about usage scenario.
Say, there are several courts in your school. They are named as court1, court2, court3, ...
well, I want today's entry-log for court1.
So, i will just ask for feb9.get("court1"), and it will return a list (ArrayList), and i can traverse that array to see the log like following:
for(EntryInfo entryinfo : feb9.get("court1") ) {
System.out.println(entryinfo.time + " : " + entryinfo.player);
}
Yeah, thats it. If i want to get the log for court2, i will retrieve the value using key "court2"
Now, lets discuss how to make this.
well today is feb9, lets make a hashmap to store today's entry log. Lets name the hashmap "feb9"
HashMap<String, ArrayList<EntryInfo>> feb9 = new HashMap<String, ArrayList<EntryInfo>>();
your school has 3 courts. Lets add 3 different keys to this hashmap so that it can hold 3 separate and corresponding entry-logs for each key(court)
feb9.put("court1", new ArrayList<EntryInfo>());
feb9.put("court2", new ArrayList<EntryInfo>());
feb9.put("court3", new ArrayList<EntryInfo>());
You can relate this with creating 3 new files named court1, court2 & court3. Each file consists of an ArrayList object, which is empty for now.
Say, now at 9:00 am, player "zineryt" enters court1. Lets entry the log into our hashmap
feb9.get("court1").add(new EntryInfo("9:00", "zineryt"));
Here feb9.get("court1") will return an ArrayList, and we used add() method to insert elements into the ArrayList.
say, at 9:50am, player "bigboy" enters court1. We can entry the log like below
feb9.get("court1").add(new EntryInfo("9:50", "bigboy"));
and it goes like this.
For tomorrow's information, we will create another new HashMap named feb10 and will follow the same steps.
Date1 (what a name) is a Map<String, Court> of courts by name, like "court1". Court has fields name and a reservation list.
So the key is (probably) a String, and the class itself is the value. One often sees, that the key/ID is also kept in the value class. So a Court object suffices to get its name.
Creating a HashMap for each Date1 is an odd and confusing approach for a HashMap can't really represent a date as we understand it. but given that this is the assignment, you have to keep information about the court number, the playtime and the competitors names. These are at least three fields, if we concat the competitors names to one String.
With only using HashMap you will probably have to use a multi-dimensional HashMap.
HashMap<Integer, HashMap<String, String>> Date1 = new HashMap<String, HashMap<String, String>>();
The outer HashMap holds the court number as the key of type Integer and the pairings as the value of type HashMap.
The inner HashMap holds the playtime as key of type String (though you might as well use the type Time) and the competitors names as value of type String.
When creating this, it is vital to generate addintional accessors to avoid tedious chained calls of Date1.get(someIntVariable).get(someStringOrTime) to receive the players names.
public HashMap<String, String> getPairingsForCourt(int court) {
return Date1.get(court);
}
public String getPlayersForCourtOnTime(int court, String time) {
return getPairingsForCourt(court).get(time);
}
By any chance getting familiar with all the aspects of HashMap requires some time. Especially if you come across mechanisms like keySet() or entrySet(). Have a look on here for a detailed yet understandable start:
A Guide to Java HashMap

Merge multiple Map and differentiate their value with different keys in java

EDIT: I have three maps with following format:
map1.put("aaa",1);
map1.put("bbb",1);
map1.put("ccc",1);
map2.put("aaa",2);
map2.put("bbb",3);
map3.put("ccc",6);
map3.put("ddd",6);
Now I want the result as list with following format:
[{"id":"aaa","map1count":"1","map2count":"2","map3count":"0"},
{"id":"bbb","map1count":"1","map2count":"0","map3count":"0"},
{"id":"ccc","map1count":"1","map2count":"0","map3count":"6"},
{"id":"ddd","map1count":"0","map2count":"0","map3count":"6"}]
How can I do this in java, help me to figure out.
you can create a class Count, with three members ex. mapCount1, mapCount2, mapCount3. Now create result map
HashMap<String, Count>() result = new HashMap<>();
Now you need to traverse these 3 maps, check map.containsKey(key), here key might be "aaa", "bbb", "ccc" etc. Now traverse first map, since map doesnt not contain any key, add key with value to result map. Now do this for 2nd, 3rd map, If key is there and then get value of count object and update count for mapCount2/3. At last for each key you can print count specific to each map.

Data updataion for same key in Hashmap

I am writing program which reads data from excel file which contains following two columns:
1- Unit code 2- quantity
Unit Code contains all units which maybe repeated also. I want to add all quantities present for same unit code without loosing any of them. I want to store this whole data in hashmap.
Please help me out.
Thanks in Advance.
You can't put duplicate keys in HashMap. But you can try something like this
Map<Key,List<Values>> map=new HashMap<>();
Now there can be list of values for selected key.
Eg:
Map<String,List<String>> map=new HashMap<>();
List<String> list=new ArrayList<>();
list.add("a");
list.add("b");
list.add("b");
map.put("a",list);
System.out.println(map);
Output:
{a=[a, b, b]}
You can store your data in a HashMap. The 'unit' can be taken as keys and the sum of 'quantities' as values. You can insert a key-value pair in your HashMap as soon as you find a 'unit' first time. Corresponding quantity will be stored as value. Now again when inserting the next record from excel, check if the new 'unit' already exists in the HashMap. If yes then the new 'quantity' should be summed to the corresponding value. If no, then a new entry will be put in the map.
The code is as follows:
Map<String,Integer> map=new HashMap<>();
//Open the file for reading using some excel API
//Read the unit and quantity line by line and assign them in `unit` and `quantity` variables
String unit=""; // Read actual unit value from file
int quantity=0; // Read actual quantity value from file
if(map.containsKey(unit)){
map.put(unit, map.get(unit)+quantity);
}
The map does not allow duplicate keys. So when you again put the same key in the map, it will overwrite the existing entry in the map. Thus the resultant map will contain the units and the sum of corresponding quantities as entries.

Storing tables in java for refrencing

So the question is regarding optimization of the code. I have a table for retirement date which im going to list below
Year of Birth Full Retirement Age
1937 or earlier.............................65
1938........................................65 years 2 months
1939........................................65-4
1934.......................................65-6
.
.
.and the list is a long list
What i want to do is to store this table in a in list object or something so that I can pass in the year of birth in a method and the list object and get back the corresponding retirement age. I dont want to have a lot of If and Else Statements in my code because the list is so damn big and the code will be confusing.
What can be a possible solution for this problem?
Thanks in advance
Try using map instead of list. Use year of birth as key, so that you can directly get the associated value from the map.
You can use map but there is a chance for duplicate keys.
Two persons can born in same year.
Use MultiMap
A Multimap that can hold duplicate key-value pairs and that maintains the insertion ordering of values for a given key. See the Multimap documentation for information common to all multimaps.
Use a map. Map is a List object with Key:Value.
Map<String, Object> map = new HashMap<String, Object>();
map.put('1937', 65);
...
To go through a map you can use this:
for (String key : map.keySet()) {
System.out.println(map.get(key));
}
You can change values for <String, Object> as you wish (Integer, Date... or whatever). Always follow the same order <KeyType, ValueType>
Store your list/table into a HashMap...then retrieve from your method, something like:
public String getRetirementAge(String yearOfBirth) {
return yourMap.get(yearOfBirth);
}
If you have data for every year i would use a java map http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html where the key is the year and the value is the retirement value.
This would give you an O(1)
If you have sparse data and you have somehow to calculate the nearest year you could either use a sorted List and use Binary search which gives you an O(logn) or even use a B-tree.
BR,
David
I would recommend that you store this information in a database, especially if the list is a very long list (which you say it is). There will be many optimizations that come from using a database. For one thing, you won't have to store that huge list in memory. For another, SQL queries for data are often much faster than data structures in code. Martin Fowler has an (admittedly old) article about this at http://www.martinfowler.com/articles/dblogic.html. The other thing you gain from putting this in a database is that this is the type of list that is likely to change. They are already talking about adjusting retirement age in order to save social security. It is much easier to update data in a database than it is to edit code and recompile / redeploy.
The type of database you use can be NoSQL or relational, embedded or online. That decision I'll leave up to you. It will be a bonus for you if there is already a database available to this application for other reasons.

How can I use a map for calculations?

I'm working on a program for class. Using a TreeMap to store IDs (String - Key) and earnings amounts (double - value). I'm importing the values from a text file using a Scanner. My problem at the moment is that I need the values to accumulate rather than overwriting with the last value read. So my question is how do you use a Map to do calculations like that? Any help would be appreciated.
There is no implicit functionality in Map. Idea behind your homework assignment is for you to learn how to insert, find, get and replace to/from a Map. There are functions for each of these and ou should use all to get this done.
When adding a new value to your map, if the key already exists, you can get the associated value, add the new value to it, and put it back into the map. Example:
// Assuming that key and value were read from your file, and that
// myMap is declared as "Map<String, Double>"
if (myMap.containsKey (key)) {
double oldValue = myMap.get (key);
value += oldValue;
}
myMap.put (key, value);
1) Check whether value with same key exists in the map
2) If it exists then read it and add the currently read value. Put it back into map

Categories