With reference to the similar question. How to dynamically create Lists in java?
I have quite a similar problem to the person asked.
In my project I have airplanes, airports and passengers for PNR record
The passenger destination airport is exported from database, but then I have to add it to a List of destination with name,airplanes.
So the database will contain like
A380, JFK, PersonA
A380, JFK, PersonB
A330, LHR, PersonC
My plan is to create the list of airport dynamically from the database and add those passenger with the same destination to it.
So currently I have peronsA and personB with JFK they will be in the same list. While in the LHR list only personC will be in LHR list, there will be hundreds of thousand record of such and hundreds of airport list to create, so I have to create such list dynamically.
But question is how do I determine if the the airport(JFK) list already exists and not create another list for that particular airport? Or is there another way to store information?
Pseudo code:
while (dbrecord =true){
if(passenger.destination == "JFK"){
List<passenger> JFK(dynamic)= new ArrayList<passenger>();
JFK(dynamic).add(passenger)
}
I'm not 100% sure if I understood the scenario, but the best way to avoid duplication is to use a Set structure such as HashSet
You could that by having a Map<String, List<Passenger>>.
Meaning: whenever you process a destination, you ask the map if it contains that destination. If yes, it already as a value which is a list; of not; you put a new List for that key, like:
Map<String, List<Passenger>> listsByDestination = new HashMap<>;
String destination = ... wherever
if (listsByDestination.contains(destination)) {
... already known
} else {
listsByDestination.put(destination, new ArrayList<>());
}
and so on.
Side not: I uppercased Passenger, because, well class names start UpperCase in Java.
Something like this might help you
Map<String, List<Passenger>> pasengerMaps = new HashMap();
if(pasengerMaps.contains("JFK")){
pasengerMaps.get("JFK").add(passenger)
}else{
pasengerMaps.put("JFK",new ArrayList<Passenger>());
}
I would use MultiMap from Google's guava library.
ListMultimap<String, Passenger> multimap = ArrayListMultimap.create();
multimap.put("destination",passenger1);
multimap.put("destination",passenger2);
You can retrive passenger list of some specific destination like this:
List<Passenger> passengerList = multimap.get("destination");
Related
I am working on a programm in Java which contains a part where I get a couple of information from my Python Server. It is a Hashmap that looks like this:
{hid=null, art=CWE, produktgruppe=23, objekt=Küche, betrag=714.989990234375, iban=DE0212, id=2812, varten=[{art=2, lz_min=24, lz_max=36, faktor=null, zinssatz=0.5, kondnr=84}], status=979}
How can I get the value of the key "zinssatz".
I tried it with
mymap.get("zinssatz");
But that always returns zero. Which is probably because it can't find the key inside my hashmap because it is build like a "Dictionary with a list of dictionaries" inside it.
Thanks for your help.
It seems to be a nested map. Have you tried the following:
((HashMap)mymap.get("varten")).get("zinssatz");
Or, if you're not sure if varten is really a HashMap, you can try the following to get the type:
System.out.println(mymap.get("varten").getClass());
Update
If varten is a HashMap stored inside an ArrayList, try the following:
((HashMap)((ArrayList)mymap.get("varten")).get(0)).get("zinssatz");
...which is the same as:
List list = (ArrayList) mymap.get("varten");
Map map = (HashMap) list.get(0);
Object zinssatz = map.get("zinssatz");
I am trying to implement a multi language interface for my project and for this I want to load the data for the 3 languages from XML file. The problem is that when I want to read values I can only do it with readValue(file,MyClass.class) which I do not want because I want to extract directly data into a set and to iterate it, not into an object.
In the XML file down, for example, I would like to extract directly the field with "english" and then to iterate through its values. The same I could do to "romanian" or "german". I find it useless to create a new class for every window I have... Is there a way to extract every language directly and to iterate trough its elements?
Here it is my XML code:
<?xml version="1.0" encoding="utf-8"?>
<langauges>
<romanian>
<flight_number>Numar zbor:</flight_number>
<depart_airport>Aeroport plecare:</depart_airport>
<destination>Destinatie:</destination>
<flight_time>Timpul de zbor:</flight_time>
<username>Utilizator:</username>
<password>Parola:</password>
<login>Log In</login>
<search_depart_destination_time>Cautare dupa aeroport de plecare/destinatie si timp</search_depart_destination_time>
<see_price_free_seats_2_locations>Vezi preturi si locuri libere intre 2 locatii</see_price_free_seats_2_locations>
<search_after_flight_number>Cauta dupa numarul zborului</search_after_flight_number>
</romanian>
<english>
<flight_number>Flight number:</flight_number>
<depart_airport>Depart airport:</depart_airport>
<destination>Destination:</destination>
<flight_time>Flight time:</flight_time>
<username>Username:</username>
<password>Password:</password>
<login>Log In</login>
<search_depart_destination_time>Search after depart/destination airport and time</search_depart_destination_time>
<see_price_free_seats_2_locations>See price and free seats between 2 locations</see_price_free_seats_2_locations>
<search_after_flight_number>Search after flight number</search_after_flight_number>
</english>
<german>
<flight_number>Flug Nummer:</flight_number>
<depart_airport>Abflug flughafen:</depart_airport>
<destination>Bestimmungsort:</destination>
<flight_time>Flugzeit:</flight_time>
<username>Nutzername:</username>
<password>Passwort:</password>
<login>Anmeldung</login>
<search_depart_destination_time>Suchen zwischen abflug/bestimmungsort und zeit</search_depart_destination_time>
<see_price_free_seats_2_locations>Sehen preis und frei plaetze zwischen 2 oerten</see_price_free_seats_2_locations>
<search_after_flight_number>Suchen ueber Flug nummer</search_after_flight_number>
</german>
</langauges>
Here, the Java method I unsuccessfully did:
XmlMapper xmlMapper = new XmlMapper();
File file = new File("languages.xml");
String xml = Files.readString(file.toPath());
String s = xmlMapper.readValue(xml, String.class);
I think you may want an iterable structure which could be changed dynamically without changing your class too. In this case, I suggest using a map.
Map<String, Map<String, String>>xmlMap = xmlMapper.readValue(xml, new TypeReference<Map<String, Map<String, String>>>() {});
or simply
Map<String, Map<String, String>>xmlMap = xmlMapper.readValue(xml, Map.class);
but I prefer the previous one because it's cleaner.
Then you could call them like
String password = xmlMap.get("german").get("password");
System.out.println(password);
In other programming languages such as JavaScript, an object is simply a map and could be changed dynamically without too much effort.
One scenario that I'm thinking about is to have a dropdown with the languages and after you choose it, you can iterate through the elements that are in that language, maybe you have a language that requires more or fewer fields, in this case, Map is a good choice.
Hope it helped you!
So I'm working on an object-oriented java project that deals with Load Management at a shipping company. A journey has an origin, location, content and destination. A journey has one or more containers where it is possible to monitor the temperature, humidity and pressure in the container. So I want to get all the journey's on which a given container has been on (the container's history). All containers used for any given journey are stored in that journey's "containerList" (arraylist).
So the idea is the method "containerHistory" should look through the arraylist "history"(which contains completed journeys) and for each journey in the "history" arraylist, should look through the array list "containerList" for each given journey and for each container in the array list "containerList" compare the given container's id to the one we are looking for( which in the below code will be represented by the string "search"
public ArrayList<Journey> containerHistory(String search, ArrayList<Journey> history){
ArrayList<Journey> containerhistorylist = new ArrayList<Journey>();
for(Journey j : history) {
for(Container c : j.getContainerList()) {
if (c.getContainerId().contentEquals(search)) {
containerhistorylist.add(j);
}
}
}
return containerhistorylist;
}
Any idea on how to improve this code or an alternative way of going about this will be greatly appreciated.
If you are comfortable with using Java 8 streams then the following code is possible:
List<Journey> containerhistorylist = history
.stream()
.filter(j -> j.getContainerList()
.stream()
.anyMatch(c -> c.getContainerId().contentEquals(search)))
.collect(Collectors.toList());
I did a bit of investigating before posting this and found that the best way to find the data i need without having to iterate through a whole List is with a HashMap. Now I've never had to use HashMaps before and it's complicating me a lot.
Given this Client class
public class Client {
private String nroClient;
private String typeDoc;}
I gotta get a typeDoc given an unique nroClient
I've gotten this far
private String getTypeDoc(List<Client> clients, String nroClient) {
Map <String, Client> map = new HashMap<String, Client>();
for (Client client : clients)
{
map.put(client.getNroClient(), client);
}
}
It just doesn't seem right at all, and I have no idea how to advance. I'd really appreciate any input. Sorry if this has been asked before, i really tried to find a solution before posting. Thanks
You've basically got it, but building the map is obviously as slow (even slower, in fact) vs. just looping the list.
Given a j.u.List instance, you CANNOT answer the question 'get me the class in this list with ID x, and do it fast'.
The solution is to remove the list entirely and have that be a map.
If you ALSO need list-like aspects (For example, you need to be able to answer the question 'get me the 18th client'), you can either use LinkedHashMap which remembers the order in which you added things, but it still doesn't have something like a .get(18) method. If need be you can have a class to represent the notion of 'Clients', internally it has BOTH a list and a map, it has an add method that adds your client to both data structures, and now you can answer both 'get me the 18th client' and 'get me the client with this ID' quickly.
Are you trying to return the match?:
private String getTypeDoc(List<Client> clients, String nroClient)
{
String typeDocFound = null;
for (Client client : clients)
{
if(client.getNroClient().equals(nroClient)
{
typeDocFound = client.getTypeDoc();
break;
}
}
return typeDocFound;
}
How can i read a list of users from the configuration file in play framework?
i have tried doing something like this:
users=[{uid:123,pwd:xyz},{uid:321,pwd:abc}]
from the play application
List<Object> uids = Play.application().configuration().getList("users");
will give me this a list of objects, if I iterate through the list i get each object as
{uid=123,pwd=xyz} and {uid=321,pwd=abc}
at this point i don't know how i can elegantly get the value of the uid, i can do some hacky job as omit the first and last bracket and parse for the before after equal sign, but it would be too ugly! any idea? (the application is written in java)
thanks
A Scala implementation that avoids the deprecated getConfigList method would rely on retrieving a Seq[Configuration] as follows:
case class UserConfig(uid: Int, pwd: String)
val userConfigs: Seq[UserConfig] = configuration.get[Seq[Configuration]]("users").map { userConfig =>
UserConfig(userConfig.get[Int]("uid"), userConfig.get[String]("pwd"))
}
Since I had recently the same problem and this is still unanswered,
here is my suggestion:
List<User> users = getConfig().getConfigList("users").stream().map(
config -> new User(config.getString("uid"), config.getBoolean("pwd"))
).collect(Collectors.toList());
As far as I know there are no tuples or anything in Java, you need to use either an object or a list with two elements. I decided to go for an object here, you can also return a list.
A list of uid's sounds to me like:
# List of UID's
users=[123,456,789] // every number represents a UID
Then you can get this list as:
List<Object> uids = Play.application().configuration().getList("users");
And then do what you want with this:
for (Iterator<Object> iterator = uids.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
System.out.println(object);
}
Is this what you are looking for?
BTW, you can read more about Play Framework configuration options: http://www.playframework.com/documentation/2.1.0/Configuration