Iterating through multiple lists - java

I have two seperate lists from a DTO i created, the two lists are containing different set of data i.e in first list lets say there are some 'userloginname' along with 2nd last updated 'status'.
In the 2nd List i have 'userloginname' with all the status record(not just the 2nd last updated status).
Is this possible if want to take each 'userloginname' from List1 and compare with each 'userloginname' in the list2 with some condition.?
thank you

Correct me if I'm misunderstanding, but how about something like this:
for (int i = 0 ; i < list1.size() ; i++) {
// Do something with "list1.get(i)" and "list2.get(i)"
}
With this you can compare items at a given index in list1 with items at the corresponding index in list2. If you want to compare every list1 member with every other list2 member, you could do something like:
for (int i = 0 ; i < list1.size() ; i++)
for (int j = 0 ; j < list2.size() ; j++) {
// Do something with "list1.get(i)" and "list2.get(j)"
}

Convert one of the lists to a map using 'userloginname' as a key.
List<LastStatusRecord> lastStatusRecords = dto.getLastStatusRecords();
List<StatusRecord> statusRecords = dto.getStatusRecords();
Map<String, FullRecord> statusRecordIndex = new HashMap<String, StatusRecord>();
for (StatusRecord statusRecord : statusRecords) {
statusRecordIndex.put(statusRecord.getUserLoginName(), statusRecord);
}
for (LastStatusRecord lastStatusRecord : lastStatusRecords) {
StatusRecord statusRecord = statusRecordIndex.get(lastStatusRecord.getUserLoginName());
// place the condition here
}

Related

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.

JAVA Get each value of arraylist

I have one arraylist that contain two list
like this
[[asd, asswwde, efef rgg], [asd2223, asswwd2323e, efef343 rgg]]
My Code is
ArrayList<String> create = new ArrayList<String>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
inner.add("asd");
inner.add("asswwde");
inner.add("efef rgg");
inner1.add("asd2223");
inner1.add("asswwd2323e");
inner1.add("efef343 rgg");
create.add(inner.toString());
create.add(inner1.toString());
i have to get all value one by one of every index of that arraylist
So what is the best way to get these all value one by one.
I am using JAVA with Eclipse Mars.
Just use two nested loops:
List<List<Object>> list = ...;
for (List<Object> subList : list) {
for (Object o : subList) {
//work with o here
}
}
You may also want to consider replacing the inner lists by proper objects.
You want to loop through the outside ArrayList and then loop through each ArrayList within this ArrayList, you can do this by using the following:
for (int i = 0; i < outerArrayList.size(); i++)
{
for (int j = 0; j < outerArrayList.get(i).size(); j++)
{
String element = outerArrayList.get(i).get(j);
}
}
Here is another verison you may find easier to understand, but is essentially the same:
for (int i = 0; i < outerArrayList.size(); i++)
{
ArrayList<String>() innerArrayList = outerArrayList.get(i)
for (int j = 0; j < innerArrayList.size(); j++)
{
String element = innerArrayList.get(j);
}
}
or alternatively again using a foreach loop:
for (ArrayList<String> innerArrayList : outerArrayList)
{
for (String element : innerArrayList)
{
String theElement = element;
}
}
It might be worth noting that your ArrayList appears to contain different types of elements - is this definitely what you wanted to do? Also, make sure you surround your strings with "" unless they are variable names - which it doesn't appear so.
EDIT: Updated elements to type String as per your update.
I would also recommend you change the type of your create ArrayList, like below, as you know it will be storing multiple elements of type ArrayList:
ArrayList<ArrayList> create = new ArrayList<ArrayList>();
Try to use for loop nested in foreach loop like this:
for(List list : arrayListOfList)
{
for(int i= 0; i < list.size();i++){
System.out.println(list.get(i));
}
}
I'm not sure if the data structures are part of the requirements, but it would be better constructed if your outer ArrayList used ArrayList as the generic type.
ArrayList<ArrayList<String>> create = new ArrayList<ArrayList<String>>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
...
create.add(inner);
create.add(inner1);
Then you could print them out like this:
for(List list : create) {
for (String val : list) {
System.out.println(val);
}
}
Othewise, if you stick with your original code, when you add to the outer list you are using the toString() method on an ArrayList. This will produce a comma delimited string of values surrounded by brackets (ex. [val1, val2]). If you want to actually print out the individual values without the brackets, etc, you will have to convert the string back to an array (or list) doing something like this:
for (String valList : create) {
String[] vals = valList.substring(1, val.length() - 1).split(",");
for (String val : vals) {
System.out.println(val.trim());
}
}

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
}

Manipulation of Java String arrays

I have a situation like
String[] ids = new String[depts.size()];
for (int i=0; i<ids.length; i++)
{
ids [i] = ("Dept" + .... )
}
So the loop looks at ids whose length is set to depts.size. But I need to add another string item to ids [i] like a "Region" + reg_num. Like the next item in ids[i] must be "Region" + reg_num and this is repeated for every department.
Since it is controlled by length, how do I do that? How do I adjust the loop to take 1 additional item. Any suggestions will be appreciated.
Thanks.
Just use a List instead of an array. Unlike arrays, lists are dynamically resizable:
final List<String> newList = new ArrayList<>(oldList);
newList.add(newElement);
EDIT if you are still using Java 6 you'll have to:
final List<String> newList = new ArrayList<String>(oldList);
instead
EDIT 2 depending on your use case, you may not even need a second list; as lists are dynamically resizable, unless you absolutely need to copy it, just keep the same list:
// first call
list.add(something);
// second call
list.add(somethingElse);
// etc etc
Without seeing more of the code however, it's hard to tell.
If you know before hand then initialize the array accordingly and add the elements as:
String[] ids = new String[depts.size()+1];//added one in the length
for (int i=0; i<ids.length; i++)
{
ids [i] = ("Dept" + .... )
}
ids[ids.length-1] = "Region"+....;
or
String[] ids = new String[2*depts.size()];//added one in the length
for (int i=0; i<ids.length; i=i+2)
{
ids [i] = ("Dept" + .... )
ids[i+1] = "Region"+....;
}
If you are trying to store a department for each id then its better to define a custom class like this:
public class Region {
String id;
String dept;
public Region(String id, String dept) {
this.id=id;
this.dept=dept;
}
// getters for id and dept
}
then define your region array like this
Region[] regions = new Region[depts.size()];
for (int i=0; i<regions.length; i++) {
regions[i] = new Region("Dept"+i, "Region"+i);
}
If I understand your reqs correctly, you can do something like this (but remember that you can hold a list of strings instead of an array, to change it dynamically):
String[] ids = new String[depts.size()*2];
for (int i=0; i<ids.length; i+=2)
{
// depts index would be i/2
ids [i] = ("Dept" + .... )
ids[i+1] = "Region"; // + ...
}

How to access array of linked list?

I've created an array of LinkedList of Connection objects using the second answer from here. That is, I've done:
LinkedList<Connection>[] map = (LinkedList<Connection>[]) new LinkedList[count];
However, I am confused as to how to access each element of the array (ie each LinkedList) and create a new node. Right now, I have:
for (int j = 0; j < numOfConnections; j++) {
map[j].add(new Connection(s.next(), s.nextDouble(), s.next()));
}
But I think this would only add a single new node to each LinkedList element of the Array. I want to loop through and add numOfConnections amount of nodes to each LinkedList element. For example, 3 nodes in map[0], 5 nodes in map[1], 2 nodes in map[2], etc.
On your example "3 nodes in map[0], 5 nodes in map[1], 2 nodes in map[2]" if numOfConnections is the amount of values you want to add to your LinkedList[k] shoudnt you map which list to add ? eg.: numOfConnections[] = {3, 5, 2};
for ( int k = 0; k < numOfConnections.length; k++ )
{
if (map[k] == null) map[k] = new LinkedList<Connection>();
for (int j = 0; j < numOfConnections[k]; j++)
{
map[k].add(new Connection(s.next(), s.nextDouble(), s.next()));
}
}
Since you have an array of LinkedList instances:
For every bucket in the array, you need to put a new LinkedList instance
You need to add Connection instances to each LinkedList, which is contained in a bucket in the array.
You are treating your array like a List, by trying to invoke add on it.
in your loop, do something like
LinkedList<Connection> list = map[j]; // get the list for this bucket in the array
if (list == null) // if there is no LinkedList in this bucket, create one
list = map[j] = new LinkedList<Connection>();
list.add(new Connection(...));
I would change your variable name map to something like lists because Java has a Map object, and it's confusing.

Categories