Naming Arraylists in a loop - Java - java

I need to create an Arraylist in a while loop with a name based on variables also in the loop. Here's what I have:
while(myScanner.hasNextInt()){
int truster = myScanner.nextInt();
int trustee = myScanner.nextInt();
int i = 1;
String j = Integer.toString(i);
String listname = truster + j;
if(listname.isEmpty()) {
ArrayList listname = new ArrayList();
} else {}
listname.add(truster);
i++;
}
The variable truster will show up more than once while being scanned, so the if statement is attempting to check if the arraylist already exists. I think I might have done that out of order, though.
Thanks for your help!

Store the ArrayLists in a Map:
Map<String, List<String> listMap = new HashMap<String,List<String>>();
while (myScanner.hasNextInt()){
// Stuff
List<String> list = new ArrayList<String>();
list.add(truster);
listMap.put(listname, list);
}
Note the use of generics (the bits in <>) to define the type of Object the List and Map can contain.
You can access the values stored in the Map using listMap.get(listname);

If I understand you correctly, create a list of lists or, better yet, create a map in which the key is the dynamic name you want and the value is the newly created list. Wrap this in another method and call it like createNewList("name").

Really not sure what you mean at all but you have some serious fundamental flaws with your code so I'll address those.
//We can define variables outside a while loop
//and use those inside the loop so lets do that
Map trusterMap = new HashMap<String,ArrayList<String>>();
//i is not a "good" variable name,
//since it doesn't explain it's purpose
Int count = 0;
while(myScanner.hasNextInt()) {
//Get the truster and trustee
Int truster = myScanner.nextInt();
Int trustee = myScanner.nextInt();
//Originally you had:
// String listname = truster + i;
//I assume you meant something else here
//since the listname variable is already used
//Add the truster concated with the count to the array
//Note: when using + if the left element is a string
//then the right element will get autoboxed to a string
//Having read your comments using a HashMap is the best way to do this.
ArrayList<String> listname = new ArrayList<String>();
listname.add(truster);
trusterMap.put(truster + count, listname);
i++;
}
Further, you are storing in myScanner a stream of Ints that will get fed in to the array, but which each have very different meanings (truster and trustee). Are you trying to read these in from a file, or user input? There are better ways of handling this and if you comment below with what you mean I'll update with a suggested solution.

Related

How to replace authors names with unique numbers in java using hashmap

I have a CSV file which is a coauthorship network.Entries are like this:
1992,M_DINE,R_LEIGH,P_HUET,A_LINDE,D_LINDE
1992,C_BURGESS,J_CLINE,M_LUTY
1992,M_DINE,R_LEIGH,P_HUET,A_LINDE,D_LINDE
1992,F_ZWIRNER
1992,O_HERNANDEZ
...
I want to replace all the authors names with unique numbers using hashmaps
I want the output to be sth like this:
M_DINE 1
R_LEIGH 2
P_HUET 3
...
and I do not want the years to be included.
Maintain a collection of author names, Read each line, split on comma, discard year, for each author if collection does not contain author name then add it to the collection. Then read from the collection and assign number.
Conceptually, you've explained everything you want to do.
You'll need a few objects.
HashMap<String, Integer> authorList = new HashMap<>();
int authorCounter = 0;
The map, obviously, and a counter to track your index.
I don't know what your main method is, but you need to process the input.
public void foo() {
// ... handle the file import through scanner in
while(in.hasNext()) {
String input = in.next();
String[] authors = input.split(',');
for(int i = 1; i < authors.length; i++) { //skip index 0 because that's the year
addAuthor(authors[i]);
}
}
}
This is a really plain addAuthor function. You probably want to extract it into hasAuthor and getAuthorId and so on, but this will just add an author if it doesn't find it with the latest iterated counter.
void addAuthor(String s) {
if(authorList.get(s) == null)
authorList.put(s, ++authorCounter);
}

Creating instance with unique name

I want to create a lot of instance in a loop but when ı try to String concatenation to generate unique name Java does not permit the operation.My opinion is here
for (Classroom classTmp : classrooms)
{
String s = "sessionClassroom" + count;
SessionClassroom s = new SessionClassroom(classTmp);
}
How can ı generate unique names to create SessionClassroom objects?Thanks for your help.
The error you are getting is because the objects are called the same:
String s = "sessionClassroom" + count;
SessionClassroom s = new SessionClassroom(classTmp);
The problem is that they are both called s. The concatenate operation ("sessionClassroom" + count) is perfectly correct.
In order to solve this problem you should rename either String s or SessionClassroom s to use a different name. Example:
String s = "sessionClassroom" + count;
SessionClassroom sc = new SessionClassroom(classTmp);
EDIT:
If what you want is having as many SessionClassroom values accessible from outside your for loop as the number of classrooms (count), then you should use a data structure like a List:
List<SessionClassroom> list = new ArrayList<SessionClassroom>();
for (Classroom classTmp : classrooms)
{
String s = "sessionClassroom" + count;
list.add(new SessionClassroom(classTmp));
}
You should use a map to hold the sessions if you want to access them by name:
Map<String, ClassroomSession> classroomSessions = new TreeMap<String, ClassroomSession>();
int count = 0;
for (Classroom classTmp: classrooms) {
count++;
String name = "sessionClassroom" + count;
SessionClassroom s = new SessionClassroom(classTmp);
classroomSessions.put(name, s);
}
Then to get access to sessionClassroom3, for instance:
classroomSessions.get("sessionClassroom3").doSomething();
Depending on how you want to access the members, it's probably best to store it as an ArrayList.
Something like
ArrayList<SessionClassroom> lSessions = new ArrayList<SessionClassroom>();
then in the loop put
lSessions.add(new SessionClassroom(classTmp));
It depends a lot on how you want to access the sessions.

Iterate through multiple array lists with same index

Im a beginner in Java. I have 3 ArrayLists and all of the ArrayLists contain data pertaining to a specific subject and hence have the same length. I want to iterate through the array and perform some operations as illustrated below:
public void example(){
ArrayList<Long> ID = new ArrayList<Long>;
ArrayList<Integer> AcNo = new ArrayList<Integer>;
ArrayList<Integer> Vnum = new ArrayList<Integer>;
//get ID and AcNo from user, compare it in the ArrayList, get the corresponding Vnum
// for the Vnum from previous step, compare it with the next Vnum and get corresponding ID and AcNo until some *condition* is satisfied.
}
How do I do this in Java? I saw examples of Iterator, but Im not sure about the correct method to do this! Please help.
If all three lists are of the same length, then iterate over them using for loop with indexes. Same indexes represents the same user in each of the three lists:
for (int i=0; i<ID.size(); i++) {
Long userId= ID.get(i);
Integer userAcNo= AcNo.get(i);
Integer userVnum= Vnum.get(i);
//if the next user exist, get the next user
if (i + 1 < ID.size()) {
Long nextUserId= ID.get(i+1);
Integer nextUserAcNo= AcNo.get(i+1);
Integer nextUserVnum= Vnum.get(i+1);
//now compare userVariables and nextUser variables
}
}
A better approach would be to have a single list of Subject objects or similar, so that each Subject contains all relevant data about itself.
class Subject {
private final long id;
private final int acNo;
private final int vnum;
/* Appropriate constructor and getters... */
}
You might also want to consider renaming the fields so that they are more descriptive.

ensuring all the ids value in the hashMap are different?

The method below (generateID())it generate a random ids, And when i store students in the HashMap i want to check if the generated id is not exist in the hashMap value and if its exists I want to generate a new id and then store it, The problem with the method store sometimes it does not store all the student because some student might have the same id and this is not allowed, So what is the best why to check that all ids are uniqe and if there is duplication the method generateid will be called again util all the ids are uniqe and then it will store it, I want to ensure that the ids values produced by generateId() are all different
private String generateId(String perfix, int numberaOfDigits)
{
for(int i=0;i<numberaOfDigits;i++)
{
perfix += randomGenerator.nextInt(9)+ 1;
}
return perfix;
}
public void store(Student student)
{
int index = 0;
studentMap.setId(generateId("AB-",1));
while(index <= studentMap.size())
{
for(Student stu : studentMap.values() )
{
if(student.getStduentID().equals(stu.getStduentID()))
{
student.setId(generateId("AB-",1));
}
}
index++;
}
}
studentMap.put(student.getStduentID(),student);
}
you can use the containsKey() method to check if an ID is already in use as key
Use an UUID. Or a sequence as already answered
If that's actually a Map implementation, you should be able to use .containsKey(). The problem is that, depending on how well written your ID generator is, this can cause significant performance issues over time. Say you have a 6 digit ID, and in a few years 80000 students have passed through the system. How many guesses will it need before it finds one of the remaining 20000 available keys?
You can get from the map with the generated Id, if it returns null, then it doesn't exist
yet.
Map<Long, Object> myMap = new HashMap<Long, Object>();
Long id = generateRandomId()
Object value = getMyObjectValue();
while(myMap.get(id) != null){
id = generateRandomId();
}
myMap.put(id, value);
I would eliminate the generateId() method altogether, and simply do this:
private int id;
then:
student.setId(id++);
I suggest to try following implementation to get unique random number each time.
Add items to the list .
Use Collections.shuffle(list); to shuffle the list .
Iterate over list and get random number each time from the given range. (For below case range is from 0 to numberOfStudent-1).
int numberOfStudent = 10;
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < numberOfStudent; i++)
list.add(i);
Collections.shuffle(list);

How do I create new variables based on the size of a List?

I have a List with say size n, and I have to dynamically create n variables ie i want to dynamically create the variables depending upon the size of the list. How can i achieve this?
Say i have List as List<Integer> year with n elements in it;
then i have to create the n Integer variables from the above list.
EDIT : If i have list with 3 elements in it the i want to create 3 variables like
a = list(0);
b = list(1);
c = list(2);
like this the list may have any number of elements then i have to create those many variables. Hope I am clear now.
thanks.
You can not create n local variables as you seem to suggest. (What would their names be?)
You need to store the variables (or rather integer values) in a List or some other Collection, and populate them within a loop:
int n = year.size();
List<Integer> theIntegers = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++)
theIntegers.add(i);
gives you year.size() number of integers (0, 1, 2, ...).
You can then access the integers through
theIntegers.get(4);
if you want to read the integer with index 4. and
theIntegers.set(4, 10);
if you want to update the integer with index 4, to the value 10.
You could in this case also create an array:
int[] ints = new int[year.size()];
for (int i = 0; i < ints.length; i++)
ints[i] = i;
There is no way I know of in Java to dynamically add variables to a scope. You can use a map as a type of variable... well, mapping instead:
final List<Integer> years = getYearList();
final Map<String, Integer> yearMapping = new HashMap<String, Integer>();
for(int year : years)
{
final String name = generateNameForYear(year);
yearMapping.add(name, new Integer(year));
}
// Later... Get "variables" out of the map:
final String variableName = "fooYear";
if (yearMapping.containsKey(variableName))
{
final Integer variableValue = yearMapping.get(variableName);
}
else
{
// "variable" does not exist.
}

Categories