Loop through ArrayList - java

I'm trying to loop through an ArrayList an get the current value of the loop instance.
public ArrayList<Double> getCurrent(double x) {
ArrayList<Double> list = new ArrayList<>();
list.add(x);
ArrayList<Double> list1 = new ArrayList<>();
double sum = 0;
for (int i = 0; i < list.size(); i++) {
sum += list.get(i);
list1.add(sum);
}
return list1;
}
Here are my JSP file. Note the loop goes through my ArrayList history, and the values I want to parse into the new ArrayList from the method getCurrent(double x) takes ret.
<% for (history his : history) {
double ret = his.getRet();
double dep = his.getDeposit();
String res = his.getRes();
if (res.equals("Loss")) {
ret = -dep;
}
%>
<h1><%=his.getCurrent(ret) %></h1>
<%} %>
This gives my an ArrayList which consist of the correct values, but NOT added with the previous values. The ArrayList now shows: [30.0, -5.0, 20.0] which is correct values. However, I want it to display: [30, 25, 45] so the values are added together with all previous values.

I believe what you want to do is to pass the double values to this function and then the function will return the list with the calculated values.
According to your code whenever the function is invoked a new Arraylist is declared every time. Thus there are no previous values, there. If you want the output to be like what you have mentioned then declare the list outside the function. Once it is outside there is no need to declared it again and again. It will retain all the previous values and when you will do your calculation it will give you your expected output.

I believe you want to get some but your declared variable is not final. Every function call will reset its value and you will not be able to get the required results. Furthermore, the statement:
sum += list.get(i);
is not as much appropriate to all compilers and IDE's and this can cause runtime error and may contain garbage if not properly handled. I prefer using this modified code.
Final double sum = 0;
for (int i = 0; i < list.size(); i++) {
sum = sum + list.get(i);
list1.add(sum);
}

Related

Find an element from list a and b such that the sum of their values is less or equal to target and as close to target as possible

https://leetcode.com/discuss/interview-question/373202/amazon-oa-2019-optimal-utilization Given 2 lists a and b. Each element is a pair of integers where the first integer represents the unique id and the second integer represents a value. Your task is to find an element from a and an element form b such that the sum of their values is less or equal to target and as close to target as possible. Return a list of ids of selected elements. If no pair is possible, return an empty list.
question was this but I had to use Lists (like <<1,1>, <2,2> <3,3>>)
my solution was something like below. I kept failing some test cases with a NullPointerException. I am trying to find out WHAT SPECIFIC INPUT(foreground, background) COULD HAVE CAUSED THIS. (the assessment website HID the error line). the problem did not have any specifications or guarantees like 0 < deviceCapacity < 1000000, so I do NOT know what was passed in
Things I checked for:
foreground and background were not null. they did not have null values (how i checked is below)
I put a System.out.println(foregroundApplications.get(i)); System.out.println(backgroundApplications.get(j)) just before initializing "sums", the goal being to see if any values were something like null or <null, null>, but they were all valid number pairs like <1,8>. (if it was null, it would have printed null right? unsure about this). example of what I saw (there were no nulls): <1, 14> <2, 14> <3, 14> <4, 14>
i checked in the beginning if the lists (foreground and background) were null with an if(foregroundApps == null), they weren't.
I can't change my code anymore, this was an assessment with obfuscated test cases which I am trying to figure out.
P.S. If there is a better approach than O(M*N) time, I would like to know
public List<List<Integer>> optimize(int deviceCapacity, List<List<Integer> foregroundApplications, List<List<Integer>> backgroundApplications)
{
TreeMap<Integer, List<List<Integer>>> map = new TreeMap<>();
for(int i = 0; i < foregroundApplications.size(); i++)
{
for(int j = 0; j < backgroundApplications.size(); j++)
{
int sum = foregroundApplications.get(i).get(1) + backgroundApplications.get(j).get(1);
if(sum<=deviceCapacity)
{
List<List<Integer>> list= new ArrayList<>();
if(map.containsKey(sum))
{
list = map.get(sum);
}
List<Integer> pair = new ArrayList<>();
pair.add(foregroundApplications.get(i).get(0));
pair.add(backgroundApplications.get(j).get(0));
list.add(pair);
map.put(sum, list);
}
}
}
if(map.size() == 0)
{
List<List<Integer>> list= new ArrayList<>();
List<Integer> emptyPair = new ArrayList<>();
emptyPair.add(null);
emptyPair.add(null);
list.add(emptyPair);
return list;
}
return map.get(map.lastKey());
}

How would you make a function with a while and for loop to return the last item in a list?

Say I had a method finalNum() where I want to use this method to pick out the final number in a list i.e. {1,2,10,12} and returns 12
What is the simplest way to do so using a for loop vs a while loop? Can someone show both? I'm new to code and trying to find a simple example.
Since Lists are based on arrays which are zero-indexed, the last element is the element at index list.size() - 1. Using List#get will suffice; there is no need for looping at all.
final List<Integer> list = List.of(1,2,10,12);
final Integer last = list.get(list.size() - 1);//12
If you really want to solve this question for educating purposes, you can take a look at these examples.
Here we loop from the beginning to the end and saving each element of the list to a variable. After we have finished looping we return the value which is by definition the last element of the list
static int finalNum(List<Integer> listOfNumbers) {
int result = 0;
for (int i = 0 ; i < listOfNumbers.length(); ++i) {
result = listOfNumbers.get(i);
}
return result;
}
You can do it the other way around, too:
static int finalNum(List<Integer> listOfNumbers) {
int result = 0;
for (int i = listOfNumbers.length() - 1; i >= 0; --i) {
return listOfNumbers.get(i);
}
throw new IllegalStateException("list contains no elements");
}
That loop goes from the end to the beginning. So the loop does not actually loop. This is mostly not what the developer wants or has intended.
The first example as a while loop
static int finalNum(List<Integer> listOfNumbers) {
int result = 0;
Iterator<Integer> iterator = listOfNumbers.iterator();
while(iterator.hasNext())
result = iterator.next();
}
return result;
}
Here we also loop from the beginning to the end storing everything in a variable which we return as result at the very end.
But after all, none of this is recommend as you can easily access the last element of a list via list.get(list.size() - 1). The above code is by no means code for production.

compare two arraylist object not working

I have two array list with name list and sum from this kind of class :
public class Factor {
private String cat;
private String kind;
private String name;
private int number;
private String id;
}
my purpose is compare this two arraylist and if they have same object , list number = sum number else sum object add to list .
this is my try so far :
int size=list.size();
for (int j=0; j<size ;j++){
for (int i = 0; i < sum.size(); i++) {
if (list.get(j).getId().equals(sum.get(i).getId())){
list.get(i).setNumber(sum.get(i).getNumber());
} else {
list.add(new Factor(sum.get(i).getId(),sum.get(i).getCat(),sum.get(i).getKind(), sum.get(i).getName(), sum.get(i).getNumber()));
}
}
}
but problem is always two condition run any way it mean do below in if list.get(i).setNumber(sum.get(i).getNumber());
and after that do below in else
list.add(new Factor(sum.get(i).getId(),sum.get(i).getCat(), sum.get(i).getKind(),
sum.get(i).getName(), sum.get(i).getNumber()));
always add list ... so where am i wrong ?
Your logic was incorrect.
Based on the comments, you want to add to list all the elements of sum that don't have a matching ID in list. For that purpose you should iterate over the elements of sum first (i.e. in the outer loop).
int size=list.size();
for (int i = 0; i < sum.size(); i++) {
boolean found = false;
for (int j=0; j<size ;j++) {
if (list.get(j).getId().equals(sum.get(i).getId())) {
list.get(j).setNumber(sum.get(i).getNumber());
found = true;
break;
}
}
if (!found) {
list.add(new Factor(sum.get(i).getId(),sum.get(i).getCat(), sum.get(i).getKind(),
sum.get(i).getName(), sum.get(i).getNumber()));
}
}
you need to make sure both list size is the same, so if they are not the same size they wont be equal
Also this is a bad practice to compare two lists, a better way would be using a Set, just convert one of the lists to a set ( time complexity O(n) ) then loop over the other list and check if all elements are in the set you created from the other list, also you need to take care of duplicate case , so if duplicate is allowed in the list you need to use a map , where the id is the key and the value is the number of occurrences , while iterating over the other list if the key is found decrement the number and check if its not getting less than zero.
From your question, it's still not clear what you are trying to achieve from this code. Do you wanna compare every element of list array with every element of sum array or u just want to compare list array with the corresponding element of sum array.
As per my understanding,
From your code, I can see that u are using nested loos.
***for (int j=0; j<size ;j++)
{
for (int i = 0; i < sum.size(); i++) {}}***
So for every list(j) array, it will compare this all the elements of sum(i) array and out which some will execute IF block and some will execute else block depending upon the condition.
If this is not what u are looking for they give some more clarity on ur question.

Get a list outside a loop

I need to get a list from another list so here is what I have done :
ArrayList<String> userList = user.getListSalarieByManager(login);
ArrayList<DHDemande> demandesList;
for (int i = 0; i < userList.size(); i++) {
demandesList = d.getDemandesForManager(userList.get(i));
}
Then I need to get the data from the list demandesList but I can't get this list outside the loop because this not have been initialized.
How can I get the data from the list inside the loop ?
That is because you haven't actually initialized your second list.
ArrayList<DHDemande> demandesList;
Should be:
ArrayList<DHDemande> demandesList = new ArrayList<DHDemande>();
By the way, the way your loop is set up sets the entire demandesList every iteration. Are you perhaps looking for List#add?
Edit: to answer you question in the comments:
Yes, you can add a list to another list using ArrayList#addAll - that would look like this:
ArrayList<String> userList = user.getListSalarieByManager(login);
ArrayList<DHDemande> demandesList = new ArrayList<DHDemande>();
for (int i = 0; i < userList.size(); i++) {
demandesList.addAll(d.getDemandesForManager(userList.get(i)));
}
Edit 2: just a small note, you can replace your for loop with a for-each, since you don't really need to know the value of i (index).
Example:
for (int i = 0; i < userList.size(); i++) {
demandesList.addAll(d.getDemandesForManager(userList.get(i)));
}
Turns into:
for (String user : userList) {
demandesList.addAll(d.getDemandesForManager(user));
}
You only need to initialize the list properly, inside or outside the loop,
but it appears that you want to add elements to the list inside the loop.
I changed your iteration over the loop to the modern java list iteration style.
// initialize variables just so this example compiles
UserProvider user = new UserProvider();
Object login = null;
DHDemandeProvider d = new DHDemandeProvider(); only
ArrayList<String> userList;
userList = user.getListSalarieByManager(login);
ArrayList<DHDemande> demandesList = new ArrayList<DHDemande>(); // construct list
for (String u: userList) {
demandesList.add(d.getDemandesForManager(u)); // add elements to list
}

How to get the list elements at each index separately using java

How to Print the list elements separately using Java
.i.e., I have a list of elements with different calculatedvalue and different updatevalues. I want to display calvalue1 and updateval1 separately into two different variables say calvalue1 into double calValue and updateval1 into double updateValue.And the loop should iterate until list becomes empty.Can anyone provide me the logic please help me.
list has at 1st line 0.98 and 23/12/2005 (list.get(0))
at 2nd line 2.3 and 08/09/2013 (list.get(1))
and so on
//here WebAvail is my class
List<WebAvail> list= new List<WebAvail>();
String query="select calvalue,updateval from sample where url='www.abc.com';
list=session.createQuery(query).list;
for(int i=0;i<list.size();i++)
{
for(int j=0;j<list.get(i);j++)
{
list.get(j);
}
}
i.e., list.get(0) gives me 1st line of the list.In that line I am having calvalue1 and updateval1 say 0.98 and 23/12/2005.I need those values seperately i.e., 0.98 into one variable and 23/12/2005 into another variable(that is I want to access seperately).list.get(0).get(0) is not valid.
How can I get that one.And also If I do like in the above code snippet It is giving me "ClassCastException:unable to cast java.lang.object to java.util.list".Here I am not having problem with query and execution of query.I checked the list by forwarding it to jsp.And jsp displaying list values.But I want list elements in WebAvail separately as I mentioned above.
for(int i=0;i<list.size();i++)
{
String a[] = list.get(j).toString().split(",");
Double a1 = Double.parseDouble(a[0].toString());
String a2 = a[1].toString();
}
Is your list.get(0) also returning the list? In this case, you can do the following:
double calValue;
Date updateval1;
List listEle = null;
for(int i=0;i<list.size();i++){
listEle = (List) list.get(i);
if(null != listEle){
if(listEle .get(0) instanceof Double)
calValue = (Double) listEle .get(0);
if(listEle .get(1) instanceof Date)
updateval1 = (Date) listEle .get(1);
}
}

Categories