Say I have an array holding employee data:
[empID, empFName, empAge, empSalary, ...]
rather than each index being [0,1,...] can I instead give the index an identifier? I'm trying to create a loop where I store an array object [employee] inside of an array, with each index of the employee array holding one of the values above empID, empFName, ...,
What I'm trying to end up with is something like this:
[Employee1[101, Dave, 35, 50000], Employee2[...]...]
is this possible in Java?
Sure. Embrace what java is, which is a nominally typed system. Emphasis on nominal: Things are supposed to have names. Thus:
#Value
public class Employee {
int id;
String name;
int age;
long salary;
}
List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee(101, "Dave", 35, 50000));
Some notes:
arrays are low level constructs you generally shouldn't be using unless you really know you need them, or its component type is primitive (int[] is much harder to avoid). Use Lists. These can shrink and grow and have funcioning implementations of equals and hashCode and the like.
You need to set up that class to have a constructor and such. If you're on java 14, you can use records; alternatively, you can use lombok's #Value, as in this example.
From what I'm understanding you're essentially describing a 2D array. While that's possible and could get you to where you want to go, I think it'd be a lot easier and teach you a lot more if you created an employee object and stored them in an arraylist! Then, you'd access the info you want with arraylist.get(i).someEmployeeMethod() where someEmployeeMethod() could be something like getName() or getId(). If you don't know what an object is, you will definitely need to.
Related
I have a list of this sorts
List<Employee>emp = Arrays.asList(new Employee("Jack", 29), new Employee("Tom", 24));
class Employee {
private String name;
private Integer id;
}
I want to insert to Employee full name List as follows:
List<Employee>empFullName = Arrays.asList(new Employee("Jack Tom", 29));
class EmployeeFullName {
private String fullName;
private Integer id;
}
How can I merge the name fields in Employee to fullName in Employee List after combining the names? I want to use Java 8 for the solution.
Notwithstanding all the reasonable questions previous commenters have posted, it feels to me like your main problem boils down to "How do I get pairs of objects out of a stream".
Once you have paired up the objects into a new collection (or stream) of pairs, you can do whatever you want to with them (i.e. make a new object out of them).
Collect successive pairs from a stream
You would still have to decide how to "merge" the pairs. In your case, it looks like you're taking the "name" and joining them together for each Pair to produce a fullName. And you're using the left-hand-side ID. That still leaves one to wonder what happened to the right-hand-side ID, but maybe with your real data-set, it's functionally duplicated..? Even so, it might be worth doing a programmatic Assert to make sure Pairs you're streaming out are consistent in that way. Otherwise one missing element in your stream and you'll be tying together all sorts of random users...
I have an object Person with the following fields:
firstName, secondName, age, nationallity, address, phoneNr.
And the list: ['John', 'Smith', '35', 'american', 'San Francisco', '+0324 235 327'].
I would like to put the values of the list into the object Person, without using the classic method of setting each value.
I want to avoid this:
person.setFirstName(list.get(0));
person.setSecondName(list.get(1));
person.setAge(list.get(2));
person.setNationallity(list.get(3));
person.setAddress(list.get(4));
person.setPhoneNumber(list.get(5));
My object has more fields than the ones I've put here as example (about 15), and I want to avoid writting a lot of code.
So my question is there a more elegant way of dumping all the values from the list into the object? I was thinking that in Java 8 maybe is there something but so far I haven't found anything.
There is no way to dump all values from the list into object, but you can add a new contructor in your Person Class, with a list as parameter like this :
public Person(List<String> list) {
this.firstName(list.get(0));
this.secondName(list.get(1));
this.age(list.get(2));
this.nationallity(list.get(3));
this.address(list.get(4));
this.phoneNumber(list.get(5));
}
and the call will be like :
Person person = new Person(list);
The other answer is good, there is one trick that can make it easier to work with though. This is especially relevant if there are a large number of entries such as the 15 mentioned in the question:
public Person(List<String> list) {
int index = 0;
this.firstName(index++);
this.secondName(index++);
this.age(index++);
this.nationallity(index++);
this.address(index++);
this.phoneNumber(index++);
}
Now you can add things to the list in any position or change the order or otherwise adjust it and don't have to manually update all the indexes. It also removes the risk of human error in accidentally getting an index wrong - although you do still need to get all the fields in the right order.
I want to store three values in a 2D type in java. I know that we can use List and ArrayList for storing 1D values but I need to store more than one field in a specific record. For example i have to enter the details for multiple columns i.e. (1,1),(1,2),(1,3) for details such aaaa, bbbb, cccc for a person and store them in one single row(which may consist of values which are other than string type). It should run in a loop and once details of a person is stored, it should store (2,1),(2,2),(2,3) i.e. again for a new person. How to do that?
And later on, how to retrieve and send the complete set to database together? Please help..
What you might want to do is to create a class that holds all of the information you want to keep related to a single record if it represents a concrete thing and use the List and ArrayList to store those.
What I mean by concrete thing is something that has a finite set of information that will stay the same over each object.
Something like:
public class Person
{
String name;
Integer age;
// etc...
}
This gives you two advantages over using something like a 2D array. First, it will make reading your code easier, since instead of having to remember that arrayName[x][0] is whatever you decide the first field is, you can access it using something like listItem.attributeName. The second advantage is that you can abstract out any common datahandling tasks as class methods instead of having to bloat your main class with it.
I am trying to build a "flat file reader." These files will have several related columns, such as "Customer Name", "Telephone," etc, but the column number will be different for each flat file; also, some flat files will have columns that others don't.
I want each of these different files to be readable by the FlatFileReader class. So I created an enum for the first flat file, where the value is an index for an array.
enum Columns { NAME, TELEPHONE, PAYMENT }
...
String[] columns = new String[3];
columns[0] = line.substring(0,29); //Name
columns[1] = line.substring(30,36); //Telephone
columns[2] = line.substring(37); //Payment
So in order to get, for example, a name from the flat file, FlatFileReader would call the method:
file.get (Columns.NAME);
and FlatFileA would look for index 0. There's going to be a wide variety of flat file classes, and I would like for each to inherit the same enum so that it's consistent; the issue is that some files won't have certain columns. So I can't do NAME, TELEPHONE, PAYMENT in the parent class (or interface) if FlatFileB doesn't have a TELEPHONE column.
How could I solve this problem? Is this how an EnumSet is used? Could each child class create an EnumSet and only add the constants it needs? If I created an EnumSet and only added NAME and PAYMENT, would PAYMENT now have a value of 1 (inside the EnumSet) or would it still have the value of 2?
EnumSet is just another implementation of the Set interface. Implementing the Set interface means it behaves just as much as a Set as any other implementation. The difference is in performance, accepted values and iteration order.
The benefit of the EnumSet is speed, the downside is that EnumSets can only have enum constants as members. Since each enum constant has a zero-based ordinal(), the EnumSet uses a bitstring representation, where each bit represents the presence/absence of an element in the set. Choosing EnumSet makes contains(All), add(All), remove(All) and retain(All) run much faster than for TreeSet and HashSet.
And no, an enum constant never changes its ordinal() (though I'm not sure whether that was what you meant).
I would suggest an ArrayList as your columns are in a sequence. I would further recommend you use an ArrayList of objects that encapsulate a Column along with details about how to gather the column from the records.
class Field {
Columns col;
int start;
int length;
}
ArrayList<Field> file1Record = new ArrayList<Field>();
// You could calculate the 0 and 29 on the fly.
file1Record.add(new Field(Columns.NAME, 0, 29));
...
I need to make a list of people and their time of arrival to a party, and when ever they leave I need to take them off this list. (the party maximum is 150)
Set would provide me that in no case I would add the same person twice.
List would provide me flexibility to start the list with few spaces (in case no one shows up).
Arrays (not sure what they provide) but I used them more often.
My idea was either to create 2 arrays one with names and what with times. When someone comes in, I save name in one and time on the other. When he/she leaves I search for his/her name, delete it and use the same index to delete the time on the other array.
A list could have one array of 2 elements, and then I will only need to add it in one location but searching would be a TINY more complicated.
Or maybe I am complicating this too much?
Map implementation:
public final class Person
{
... remainder left to the student ...
}
Map<Person, Date> currentPartyAttendees; // date is arrival time.
Set implementation:
public final class PartyAttendee
{
... person details ...
Date arrive;
int hashcode()
{
... use Apache HashCodeBuilder ...
}
boolean equals(Object other)
{
... implementation left to student. Use Apache EqualsBuilder ...
}
}
Set<PartyAttendee> currentPartyAttendees;
Using a HasMap would suit your purpose, as you can use the person's name as a key to add and retrieve the entry for the person, and it offers constant time performance, so regardless of how large the set grows, the performance should remain consistent.
The way you've described your use-case, why not consider the HashMap, or some other Map based implementation?
Unless of course, there's a binding for you to use a List [or similar] based data structure.
Just use a List<> and a Data structure the represents guest.
Subclass List to mark the arrival and departure time and add/remove methods. You can also use set, but then you'll have to generate a hashCode and equals method. I'm not sure you want to do that, cause people may have the same names (unless you have other data like SSN, bday, middle name etc)
public Class Guest{
private String firstName, lastName;
private long arrivalTime, departureTime;
....
}
public class MyGuests extends ArrayList<Guest>{
#Overide
public void add(Guest g){
//record arrival time here
super.add(g)
}
#Overide
public void remove(Guest g){
//record departure time here
super.remove(g);
}
}
I think you can use arrays as well, and, instead two arrays, use an arrays of 'Person' model, that holds the name of the person, arrive time and leave time. Before you insert on array, you can verify if the list already contains this person.
ps: don't forget to overwrite equals() and hashCode() in your model
LinkedHashMap - a container of key-value pairs that maintains the order of their insertion. The key would be the person (a simple String or a designated class), the value would be the time of arrival, e.g. a Date.