I am having an issue with adding elements to an ArrayList. I created a POJO like my array list.
public class GroupUserMapping {
String group;
ArrayList<String> users;
//setters getters constructor
}
I have a function where I am reading a text file to get Groups which I stored in groups array now for those groups I need to loop through all the records in other text file and get all the users who have this group mapping and according to my condition I am trying to add elements to the Pojo ArrayList like this:
ArrayList<GroupUserMapping> usergroups = new ArrayList< GroupUserMapping >();
ArrayList<String> users = new ArrayList<>();
ArrayList<String> groups = getGroups();// This used for lopping I have certain groups.
Scanner s = null;
String group="";
for(int i= 0;i<groups.size();i++ ){
s = new Scanner(new File(getClass().getClassLoader().getResource(mappingFile).getFile()));
s.useDelimiter("\r\n");
group=groups.get(i);
users.clear();
while (s.hasNext()) {
String aLine = s.next();
String[] value = aLine.split(":");
if(group.equalsIgnoreCase(value[0]))
{
LOGGER.info(group+":"+value[1]);
users.add(value[1]);
}
}
GroupUserMapping groupUserMapping = new GroupUserMapping(group,users);
usergroups.add(groupUserMapping);
s.close();
The issue is when I am reading for Group say G1 I got users u1,u2 and these mapping is correctly stored in usergroups but next loop when I am searching for Group G2 I have users U2,U3. Here in the 2nd loop, it is also updating 1st Group values as well. Ideally my elements should be G1->U1,U2 and G2-> U2,U3 but my code is adding elements like this. G1->U2,U3 G2-> U2,U3. What I am doing wrong here?
The line users.clear(); is causing the issue.
In the first iteration you add users 1 and 2 to that list. Then in the constructor you are passing this list.
GroupUserMapping groupUserMapping = new GroupUserMapping(group,users);
Now in the second iteration, you clear the loop and then add users 2 and 3. Since the first group has the reference to the same list, G1's user list is also cleared and user 2 and 3 are added.
You need to replace the users.clear(); with
users = new ArrayList<String>();
In the above case, the data is unchanged, only the users variable now points to a different location. Hence there won't be any changes to the list of G1.
Related
I have an array of company names and I want to see if they match a certain value.
In fact, I want a list of all non-matching values. Something like this:
"One or more companies: [company1], [company2] are not equal to [checkCompany]
Example:
checkCompany = "GM"
companies = ["GM", "GM", "Ford"]
In this case there would only be one company not equal to "GM" but there could be more than one.
This function should simply work, its arguments are the companies array and the checkCompanies string that you want to check against.
The function then returns tempList which includes all the values that do not match with checkCompanies string.
import java.util.ArrayList;
public ArrayList<String> checkList(ArrayList<String> companies, String checkCompany) {
ArrayList<String> tempList = new ArrayList<String>();
for(int i = 0; i < companies.size(); i++) {
if(!companies.get(i).equals(checkCompany)) {
tempList.add(companies.get(i));
}
}
return tempList;
All you would then have to do is format the return to give you the string you want to output!
checkCompany = "GM"
companies = ["GM", "GM", "Ford"]
nonMatchedCompanies = list()
for(String company : companies){
if(!company.contains(checkCompany)
nonMatchedCompanies.add(company)
}
nonMatchedCompanies is the result which will contain all not matched companies from the list. This will check if the checkCompany is part of company name.
Scenario:
As seen in the above screen there are 2 ids in the same row which are seperated by comma.
My method is there where i get the lastest id.The Problem over here is it fetches both the Ids.
Since i use the id to search i dont want both the Ids.
Below is my method which i use to Fetch the Ids
public static HashMap<String, String> Values;
public static void PlanningScreenFetchPlanningandDemandID(WebDriver driver) throws InterruptedException
{
Values = new HashMap<String, String>();
List<WebElement> tableValue = driver.findElements(By.xpath("//table//tr//td[contains(#class,'mat-column-demandId')]//span"));
int tableValueSizes = tableValue.size();
WebElement latestIds = driver.findElement(By.xpath("(//table//tr//td[contains(#class,'mat-column-demandId')]//span)["+tableValueSize +"]"));
Values.put("latestDataId", latestIds.getText());
System.out.println(Values.put("latestDataId", latestIds.getText()));
String Id = AppXPathsConstants.columnInputEntryXpath_replace.replace("XXXX", "ID") ;
inputEntry(driver, Id , Values.put("latestDataId", latestId.getText()));
}
If latestIds.getText() prints this 4306, 4307 in the console, and your intention is to get only id (I'd assume the first one), then you can try the below code :
String firstID = latestIds.getText().split(",")[0];
String secondID = latestIds.getText().split(",")[1];
also if there are trailing spaces, make sure to use .trim to remove them.
As I understand you are getting Ids here:
latestIds.getText()
So you can simply split the Id values as following:
String bothIds = latestIds.getText();
String [] ids = bothIds.split(",");
To give better answer we need to get more details about that web page, not a pictures
UPD
You can get each separate id from the array above simply as following:
First id value:
ids[0]
The second id value:
ids[1]
I am currently working on a project where I need to check an arraylist for a certain string and if that condition is met, replace it with the new string.
I will only show the relevant code but basically what happened before is a long string is read in, split into groups of three, then those strings populate an array. I need to find and replace those values in the array, and then print them out. Here is the method that populates the arraylist:
private static ArrayList<String> splitText(String text)
{
ArrayList<String> DNAsplit = new ArrayList<String>();
for (int i = 0; i < text.length(); i += 3)
{
DNAsplit.add(text.substring(i, Math.min(i + 3, text.length())));
}
return DNAsplit;
}
How would I search this arraylist for multiple strings (Here's an example aminoAcids = aminoAcids.replaceAll ("TAT", "Y");) and then print the new values out.
Any help is greatly appreciated.
In Java 8
list.replaceAll(s-> s.replace("TAT", "Y"));
There is no such "replace all" method on a list. You need to apply the replacement element-wise; the only difference vs doing this on a single string is that you need to get the value out of the list, and set the new value back into the list:
ListIterator<String> it = DNAsplit.listIterator();
while (it.hasNext()) {
// Get from the list.
String current = it.next();
// Apply the transformation.
String newValue = current.replace("TAT", "Y");
// Set back into the list.
it.set(newValue);
}
And if you want to print the new values out:
System.out.println(DNAsplit);
Why dont you create a hashmap that has a key-value and use it during the load time to populate this list instead of revising it later ?
Map<String,String> dnaMap = new HashMap<String,String>() ;
dnaMap.push("X","XXX");
.
.
.
dnaMap.push("Z","ZZZ");
And use it like below :
//Use the hash map to lookup the temp key
temp= text.substring(i, Math.min(i + 3, text.length()));
DNAsplit.add(dnaMap.get(temp));
This function loops through a dictionary (allWords) and uses the
getKey function to generate a key. wordListMap is a HashMap> so I need to loop through and put the key and and a List. If there is not a list I put one if there is I just need to append the next dictionary word. This is where I need help. I just can't figure out the syntax to simply append the next word to the list that is already there. Any Help would be appreciated.
public static void constructWordListMap() {
wordListMap = new HashMap<>();
for (String w : allWords) {
int key = getKey(w);
if (isValidWord(w) && !wordListMap.containsKey(key)) {
List list = new ArrayList();
list.add(w);
wordListMap.put(key, list);
} else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.put(key, wordListMap.get(key).add(w));
}
}
}
map.get(key).add(value)
Simple as that.
So I've gathered that you want to, given HashMap<Integer, List<String>>, you'd like to:
create a List object
add String objects to said List
add that List object as a value to be paired with a previously generated key (type Integer)
To do so, you'd want to first generate the key
Integer myKey = getKey(w);
Then, you'd enter a loop and add to a List object
List<String> myList = new List<String>;
for(int i = 0; i < intendedListLength; i++) {
String myEntry = //wherever you get your string from
myList.add(myEntry);
}
Lastly, you'd add the List to the HashMap
myHash.put(myKey, myList);
Leave any questions in the comments.
else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.put(key, wordListMap.get(key).add(w));
}
If you want to add a new value to your list, you need to retrieve that list first. In the code above, you are putting the return value of add into the table (which is a boolean), and that is not what you want.
Instead, you will want to do as Paul said:
else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.get(key).add(w);
}
The reason this works is because you already added an ArrayList to the table earlier. Here, you are getting that ArrayList, and adding a new value to it.
I've created a method to read a text file and pull out the name of a contact from each line.
private ArrayList<String> readContacts()
{
File cFile = new File ("Contacts.txt");
BufferedReader buffer = null;
ArrayList <String> contact = new ArrayList<String>();
try
{
buffer = new BufferedReader (new FileReader (cFile));
String text;
String sep;
while ((sep = buffer.readLine()) != null)
{
String [] name = sep.split (",");
text = name[1];
contact.add(text);
}
}
catch (FileNotFoundException e)
{
}
catch (IOException k)
{
}
return contact;
}
I'm trying to populate a JList with each contacts name using the method I've created above using this:
model = new DefaultListModel();
for (int i = 1; i < readContacts().size(); i++)
{
ArrayList <String> name = readContacts();
model.addElement(name);
}
nameList = new JList (model);
add(nameList);
When I run the program, the JList only has the numbers 1-10, instead of each of the contacts names. Is the problem I'm running into here logical or problems with syntax? Any help would be great, thanks!
Don't call readContacts() from within the for loop as that makes no sense. You're creating a new ArrayList multiple times and then adding the entire same ArrayList to your JList, in other words, each element in your JList is an ArrayList (???).
Instead call it in the for loop condition or before the for loop.
Do not have empty catch(...) blocks. Doing this is the programming equivalent of driving your car with your eyes closed -- very dangerous.
For example,
model = new DefaultListModel();
// call readContacts() only *once*
for (String name: readContacts()) {
model.addElement(name);
}
I would say we may create a ArrayList object first, then assign the new readContacts() to this object. After that, read the elements in a loop, if you want, you can print out each elements in the ArrayList to ensure those are you want.
If your program is running, you do not have a syntax problem. Your program is running, but is not giving the expected results. That is a logical problem.
You state:
"the JList only has the numbers 1-10, instead of each of the contacts names."
When I look at your readContacts(), you populate your contact List with name[1]. What is in name[1]? I'm lead to believe that name[1] contains 1 - 10 as you read through your file. What is in name[0], or name[2] or name[3], if they even exist. So my first suggestion will be to try a different index for name since name[1] isn't giving you the right result.
Second, you populated your model with the ArrayList name, instead of using the contents of name. Follow Hovercraft Full Of Eels example to populate your model.