I'm almost at the end of my final project in the university, I'm trying to control my inStock with my current Stock of articles.
My stock contains the following attributes:
int idMercaderia;
int cantidad;
int idSucursal;
I have two lists that contains Inventario type POJOs:
List <Inventario> stock = new InventarioDAO().findAll();
List <Inventario> inStock = new ArrayList <Inventario>();
Before persist in the database, I want to compare the attribute idMercaderia in both of 'em, if they're the same don't create another entry and just add the quantity cantidad to the current stock and do a saveOrUpdate() if not just create another entry.
I'm really stuck in this part and currently run out of ideas after trying iterate both Lists but I can't figure out the stock thingy.
Any help/code will be really appreciated.
you need to implement an equals() method if not already happened in the Inventario to compare idMercaderia in there. then
for(Inventario item: stock){
if(inStock.contains(item)){
item.cantidad++;
}
}
Create a Map<Integer, Inventario> of your first list to map an idMercaderia to one Inventario. Then iterate your second list and check for each item the corresponding one in the map.
Map<Integer, Inventario> map = new HashMap<Integer, Inventario>();
for (Inventario item : stock) {
map.put(item.getIdMercaderia(), item);
}
and
for (Inventario item : inStock) {
int idMercaderia = map.getIdMercaderia();
Inventario inventario = map.get(idMercaderia);
if (inventario == null) {
// error handling
continue;
}
if (item.getCantidad() == inventario.getCantidad() {
// handle
}
}
Related
So for one of my projects I have to make teams for a game based off of last names, They are supposed to be as diverse as possible, so the "smith" family will only be added onto the same team as another "smith" family if there is no other team without a "smith" already.
I am given an ArrayList with a list of Participants, whose last names are included. I just need to figure out how to sort this so that the ArrayList is diverse and I would just run through the ArrayList and assign them to the teams
ArrayList<Participant> list = tourney.getUnattatchedParticipants();
//need to sort list somehow
I would approach your Problem like this;
Create a Data Container that keeps all the teams. Since we are not sure how many teams we will have, I would make this data container Dynamic (e.g. ArrayList)
I would start iterating your ArrayList with Participants and for each I would check Team Nr.1 if it contains a Participant which has a similiar (same, or contains part of the surname) surname.
If it does, check Team Nr.2..
If we reach the last team and it already contains a Partipant which is similar to the last one, then we create Another team.
Maybe something like this:
public ArrayList<ArrayList<Participant>> divideParticipantsIntoTeams(ArrayList<Participant> participants)
{
ArrayList<ArrayList<Participant>> groups = new ArrayList<>(); // This keeps our groups
groups.add(new ArrayList<>()); // We create our first group.
// We iterate over all given participants
participants.forEach(participant ->
{
boolean contains = true; // Variable that shows us if we already have it in a group
// We iterate over all the groups and check if it is contained in them
for(ArrayList<Participant> group: groups)
{
// Checks if a participant is found with a similar surname
contains = containsParticipant(group, participant);
// If it doesn't contain such a participant then we add it to the group and we go out of the loop.
if(!contains)
{
group.add(participant);
break;
}
}
// If we iterate all the groups and when finished they all contain some similar Participant, create a new one.
if(contains)
{
groups.add(new ArrayList<>());
ArrayList<Participant> newGroup = groups.get(groups.size() - 1); // Getting the just created group
newGroup.add(participant); // Adding the participant to it
}
});
return groups;
}
public boolean containsParticipant(ArrayList<Participant> group, Participant participant)
{
for(Participant groupParticipant: group)
{
// this could use some fine tuning, depends on how you want it.
if(groupParticipant.getLastName().contains(participant.getLastName()))
{
return true;
}
}
return false;
}
So I'm going crazy with this one. This is for an assignment and can't seem to get this to work at all!!
I have the following HashMap:
HashMap<String, ArrayList<Team>> teams;
(Team being another class to obtain the details of the teams)
What I need to be able to do is get the List of teams for the Key(String) from the above HashMap, and assign the List to a local variable I have declared:
List<Team> results = teams.get(division);
But this is where I get stuck. I have no idea how I'm suppose to complete this task.
As a further note "division" is the Key used in the HashMap. The ArrayList is a list of teams that belong to the division.
I have tried the below, which does not compile at all. Really not sure how I can get this to work!!
public void recordResult(String division, String teamA, String teamB, int teamAScore, int teamBScore)
{
List<Team> results = teams.get(division);
for (String i : teams.keySet())
{
results = new ArrayList<Team>();
results.add();
}
}
**You can ignore the arguments after the "String division". These will be used later.
Iterate over the entrySet() of the Map. Now you can fetch each List for that specific key and proceed further. Something like:
for (Entry<String, ArrayList<Team>> entry : teams.entrySet()) {
// extract the value from the key using `teams.get(entry.getKey())`
// proceed further with the value obtained
}
I want to create a HashMap that has a key of type String and a value of a List of Objects that is set up in another class.
The code I have tried works in that it adds a key and a value to the map, but wont add multiple values to 1 key. I.E I would like Key x to have values 1,2 and 3 but it just seems to overwrite the last value rather than add another one.
This is my current code:
public class LeagueAdmin {
private Map<String, List<Team>> teams;
/**
* Constructor for objects of class LeagueAdmin
*
*/
public LeagueAdmin() {
this.teams = new HashMap<>();
}
public void addTeam(String division, Team team) {
if(!this.teams.containsKey(division))
{
List<Team> Team = new ArrayList<>();
Team.add(team);
this.teams.put(division, Team);
} else {
List<Team> newTeam = this.teams.get(division);
}
}
}
As I said, when I add multiple values to the key string 'top' for example I expect 'top' to show me all the values added to it, instead it only shows the latest one added. Also as mentioned the Team object is handled in a separate class file.
Your else is incomplete. You make a list but never add to it when it sees that the key division exists. Add
newTeam.add(team);
to your else statement
Ive been searching SO about this question and most only have the problem with two arrays comparing by have a nested loop. My problem is quite the same but on a bigger scale. Suppose I have a 100 or thousand user on my app, and each user has the list of item it wants.
Something like this
User1 = {apple,orange,guava,melon,durian}
User2 = {apple, melon,banana,lemon,mango}
User3 = {orange,carrots,guava,melon,tomato}
User4 = {mango,carrots,tomato,apple,durian}
.
.
Nuser = ...
I wanted to see how many apples or oranges was listed from all the users array. So I am basically comparing but on a bigger scale. The data isn't static as well, A user can input an unknown fruit from the developers knowledge but on the users knowledge they can put it there so there can be multiple users that can put this unknown fruit and yet the system can still figure out how many is this unknown item was listed. Keep in mind this is a dynamic one. User can reach for example a 100 users depending how popular an app would be. I can't afford to do nested loop here.
PS this is not the exact problem but it is the simplest scenario I can think of to explain my problem.
PS: just to clarify, I dont intend to use 3rd party lib as well like guava. I am having a problem on proguard with it.
Edit
Just read that Original poster cannot use Java 8, which is a pity, because this would realy make it very easy!
Java 7 solution
final Map<String, Integer> occurencesByFruit = new HashMap<>();
for (User user : users) {
String[] fruits = user.getFruits();
for (String fruit : fruits) {
final Integer currentCount = occurencesByFruit.get(fruit);
if (currentCount == null) {
occurencesByFruit.put(fruit, 1);
} else {
occurencesByFruit.put(fruit, currentCount + 1);
}
}
}
Java 8 solution
I'd stream the users, flatMap() to the actual fruit elements, and then use Collectors.groupingBy() with a downstream collector Collectors.counting().
This will give you a Map where the keys are the fruits, and the values are the occurrences of each fruit throughout all your users.
List<User> users = Arrays.asList(/* ... */);
final Map<String, Long> occurencesByFruit = users.stream()
.map(User::getFruits)
.flatMap(Arrays::stream)
.collect(Collectors.groupingBy(f -> f, Collectors.counting()));
Seems it is a good possibility to use HashMap<Item, Integer> fruits. You could iterate over all Users (you would need to store all Users in some kind of list, such as ArrayList<User> users) and check the list of items chosen by each User (I suppose User should have a field ArrayList<Item> items in its body to store items). You could achieve it with something like that:
for (User user : users) { // for each User from users list
for (Item item : user.items) { // check each item chosen by this user
if (fruits.containsKey(item) { // if the fruit is already present in the items HashMap increment the amount of items
int previousNumberOfItems = fruits.get(item);
fruits.put(item, ++previousNumberOfItems);
else { // otherwise put the first occurrency of this item
fruits.put(item, 1);
}
}
}
I would either create an ArrayList containing a HashMap with strings and ints or use two ArrayLists (one of type String and one of type Integer). Then you can iterate over every entry in each of the user arrays (this is only a simple nested loop). For every entry in the current user array you check if there is already the same entry in the ArrayList you created additionally. If so, you increment the respective int. If not, you add a string and an int. In the end, you have the number of occurrences of all the fruit strings in the added ArrayLists, which is, if I understood you correctly, just what you wanted.
I have a hashmap for orders and another one for orderitems. A method which puts the data into the hashmaps is executed like this:
// THIS ONE ADDS THE ORDERS
// (int orderNumber, String Datum, String salesperson, int customernumber)
mainController.addBestallning(500, "2012/01/01", "Hendrik Gustafsson", 1001);
// THIS ONE ADDS THE ORDERED ITEMS
// (int orderNumber, int linePos, Artikel product, int amount, double price)
mainController.addBestallningsOrderRad(500, 1, mainController.getAllaArtiklar().get(101), 5, 100.00);
Once I find an order by its ordernumber, how do I find the ordereditems?
The only link I have now is the ordernumber, which I save in orderitemshashmap, so I assume some sort of iteration needs to take place, find the matches and return the results.
I tried doing this and got it to work, but only under condition that all of the orderitem positions are also unique.
So, if I was to add another order like this:
mainController.addBestallning(501, "2011/05/02", "Sven Karmageddon", 1002);
mainController.addBestallningsOrderRad(501, 1, mainController.getAllaArtiklar().get(101), 5, 100.00);
I could not find the orderitems for order 501.
Here is what I tried so far. Made a method to find all orders of a customer:
public HashMap<Integer, Bestallning> getAllaKundOrdrar() {
HashMap<Integer, Bestallning> allaKundOrderHashMap = new HashMap<>();
//iterate through all orders
//find the ones which belong to customerid
//place them in allaKundOrderHashMap
//return allaKundOrderHashMap
Iterator iter = tmpBestallningsregister.getAllaBestallningar().keySet().iterator();
while (iter.hasNext()) {
Integer key = (Integer) iter.next();
//String value = (String) controller.getAllaKunder().get(key).getKundNamn();
if ((customerNrToFindOrdersFor) == getAllaBestallningar().get(key).getKundNr()) {
//found an order for this customer, putting it in the hashmap
allaKundOrderHashMap.put(key, getAllaBestallningar().get(key));
}
}
return allaKundOrderHashMap;
}
A method to find all ordereditems from all customers (100% wrong to search like this, I know) and get the ones beloning to a specific order:
//RETURN OF ORDERRADERS HASHMAP FOR SPECIFIC ORDER VIA ORDERREGISTER
public HashMap<Integer, BestallningsOrderRad> getAllaBestallningsBestallningsOrderRader() {
HashMap<Integer, BestallningsOrderRad> allaBestallningsOrderRaderHashMap = new HashMap<>();
//iterate through all orderrader
//find the ones which belong to orderid
//place them in allaKundOrderRaderHashMap
//return allaKundOrderRaderHashMap
Iterator iter = tmpBestallningsregister.getAllaBestallningsOrderRader().keySet().iterator();
while (iter.hasNext()) {
Integer key = (Integer) iter.next();
if ((orderNrToFindOrderRaderFor) == tmpBestallningsregister.getAllaBestallningsOrderRader().get(key).getBestallningsNr()) {
//found an orderrad for this order, putting it in the hashmap
//allaBestallningsOrderRaderHashMap.put(key, getAllaBestallningsOrderRader().get(key));
allaBestallningsOrderRaderHashMap.put(key, getAllaBestallningsOrderRader().get(key));
}
}
return allaBestallningsOrderRaderHashMap;
}
Anyone care to tell me what is it that I am doing wrong?
I've been at this for 20 hours straight...
Don't use two different Map, but only one. What you need is to properly define a Order class that holds all the order data (including suborders, which are sheldom used outside the order) and use just a Map<Integer,Order>
If you insist in having two separate Maps, the second uses the same id but stores a List (it looks like you want it ordered) of suborders.
private Map<Integer, Order> orders;
private Map<Integer, List<SubOrder> suborders;
Stopping a moment before beginning to code and thinking the more appropiate data structures will usually save you a lot of "hell" later.