Java: Storing an Array into an Array? - java

Is it possible to store three string values added into an array (studentName), and store that into a different array so it can be found later?
Basically my main goal is to store a name, user id, and a balance (fullName, idName, 300).
And add that into a "super(?)" array so when people type down, it finds the fullName and pulls the information from there.

You can create a class
public class Student {
private String name;
private String id;
private int balance;
}
and then you can create a list of these objects:
List<Student> list = new ArrayList<Student>();
Map<String, String> map = new HashMap<String, String>();
then:
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
and then:
map.put("name", "Thomas");
map.put("id", "Thomas id");
map.put("balance", ""300);
listOfMaps.add(map);
Anyhow, be careful. You will have to keep numbers (f.e. balance) as a String and after you will need to map it.

Well, I believe you are talking about something like Jagged Array which is available in C# but for java, we can do it in some other ways... like creating a class and manipulating it as Generic List implementation...
public class Student {
private String name;
private int id;
private int balanace;
public Student(){}
public Student(String name, int id, int balance){
this.name = name;
this.id = id;
this.balanace = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBalanace() {
return balanace;
}
public void setBalanace(int balanace) {
this.balanace = balanace;
}
}
In some other class where you would want to manipulate
public class ManipulateData {
public static void main(String[] args){
Student student1 = new Student("James", 1, 500);
List<Student> list = new ArrayList<Student>();
list.add(student1);
for(Student s: list){
System.out.println("Name : " + s.getName());
System.out.println("ID : " + s.getId());
System.out.println("Balance : " + s.getBalanace());
}
}
}

Related

In Java, how do you create an ArrayList, with one element of that list being another ArrayList, that is unique for each element?

So for example.
I have an ArrayList of people. Created through a people object that contains a name, address, age, etc.
How would I then add another list to that, allowing a unique list of hobbies for each person?
So I could have:
James, 32, England, (Football, Tennis)
Chloe, 21, Wales, (Art)
Tried a few things and struggling with it.
import java.util.ArrayList;
public class People {
int id;
String name;
ArrayList<String> hobbies;
public People(int id, String name, ArrayList<String> hobbies) {
this.id = id;
this.name = name;
this.hobbies = hobbies;
}
public People(String name) {
this.name = name;
}
public People() {
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "People [id=" + id + ", name=" + name + ", hobbies=" + hobbies + "]";
}
}
import java.util.ArrayList;
public class Runner {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<People> arrayPeople = new ArrayList<>();
ArrayList<String> hobbies = new ArrayList<>();
hobbies.add("Football");
hobbies.add("Tennis");
arrayPeople.add(new People(1,"Paul", hobbies));
hobbies.add("Golf");
arrayPeople.add(new People(2,"James", hobbies));
System.out.println(arrayPeople);
}
}
This creates a hobby list that is the same for each person, not unique.
This creates a hobby list that is the same for each person, not unique.
That's because member hobbies in [Paul] People object has same value as member hobbies in [James] People object, since they are assigned the same value in method main of class Runner. Hence when you change hobbies variable, in method main of class Runner, you are changing for both Paul and James.
The simplest solution is to change the class constructor so that it creates a copy of the hobbies parameter and assigns the copy to the hobbies member:
public People(int id, String name, List<String> hobbies) {
this.id = id;
this.name = name;
this.hobbies = new ArrayList<>(hobbies);
}
However, I suggest that you add methods to class People to manipulate hobbies member, including:
addHobby for adding a hobby
removeHobby for removing a hobby
clearHobbies for removing all hobbies
getHobbies that returns a copy of hobbies (so that code that calls the method cannot change hobbies)
Below code demonstrates.
Note that you should always use the interface – in this case java.util.List – rather than the implementation – in this case ArrayList – in the API so that you can change class People without having to change its API. If you change the API of class People then all other classes that use class People – like class Runner in the code in your question – will need to be changed as well.
import java.util.ArrayList;
import java.util.List;
public class People {
private int id;
private String name;
private List<String> hobbies;
public People(int id, String name, List<String> hobbies) {
this.id = id;
this.name = name;
this.hobbies = new ArrayList<>(hobbies);
}
public People(int id, String name) {
this(id, name, new ArrayList<String>());
}
public People() {
this(0, "");
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addHobby(String hobby) {
if (!hobbies.contains(hobby)) {
hobbies.add(hobby);
}
}
public void clearHobbies() {
hobbies.clear();
}
public List<String> getHobbies() {
return List.of(hobbies.toArray(new String[]{}));
}
public void removeHobby(String hobby) {
if (hobbies.contains(hobby)) {
hobbies.remove(hobby);
}
}
#Override
public String toString() {
return "People [id=" + id + ", name=" + name + ", hobbies=" + hobbies + "]";
}
public static void main(String[] args) {
List<People> arrayPeople = new ArrayList<>();
People paul = new People(1,"Paul");
paul.addHobby("Football");
paul.addHobby("Tennis");
People james = new People(2,"James");
james.addHobby("Football");
james.addHobby("Tennis");
james.addHobby("Golf");
arrayPeople.add(paul);
arrayPeople.add(james);
System.out.println(arrayPeople);
}
}
Running the above code prints the following:
[People [id=1, name=Paul, hobbies=[Football, Tennis]], People [id=2, name=James, hobbies=[Football, Tennis, Golf]]]
The question seemed unclear to me, however I assume that you created lists such as
[name,age,location]
However, this is not an object. If you create a person object, you can add features inside it. So that when you create a person object, then you will have access to add/edit new features. In your case, your features must be:
Name
Age
Location
List (Whatever you name it, type of it must be an arraylist).
To have a list of people:
class Person{
String name;
int age;
String Address;
...
}
and
ArrayList<Person>
For the people class, if you need each hobby in hobbies to be unique you can have a Set class to store hobbies.
class Person{
String name;
int age;
String address;
Set<String> hobbies;
...
}
If the order does not matter you can use HashSet To maintain the order you can use TreeSet or LinkedHashSet.
class person{
String name;
int age;
String address;
TreeSet<String> hobbies;
...
}
class Person{
String name;
int age;
String address;
LinkedHashSet<String> hobbies;
...
}
To add a hobby to a person.
String hobby = "a hobby";
person.add(hobby);
To add hobbies to a person;
String hobby1 = "hobby1";
String hobby1 = "hobby2";
...
Set<String> hobbies = new TreeSet(); // or Set<String> hobbies = new LinkedHashMap();
hobbies.add(hobby1);
hobbies.add(hobby2);
...
person.addAll(hobby);
For another person with the same hobbies, you need to copy the hobbies, then modifying the hobbies of the second person will not affect the hobbies of the first person.
Set<String> new_hobbies = new TreeSet(old_hobbies); // or new LinkedHashSet(old_hobbies);
another_person.addAll(new_hobbies);

I need to get the max from a Employee class from a Farm class

I need to find and display the the employee who has the maximum salary from the Farm.
this is what I got so far
public class Employee implements Comparable<Employee> {
private String name;
private Integer salary;
public Employee (String name , Integer salary) {
this.name = name;
this.salary = salary;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public Integer getSalary() {
return salary;
}
public String toString() {
return name + " " + salary;
}
public int compareTo(Employee emp) {
return this.salary.compareTo(emp.getSalary());
}
}
Employee class
public class Farm {
private String name;
private Integer surface;
List<Employee> emp = new ArrayList<Employee>();
public Farm(String name , Integer surface) {
this.name = name;
this.surface = surface;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSurface(Integer surface) {
this.surface = surface;
}
public int getSurface () {
return surface;
}
public String toString() {
return name + " " + surface;
}
public void makeList(String ename , Integer esalary) {
this.emp.add(new Employee(ename,esalary));
}
public void getList() {
for(Employee el : emp)
System.out.println(el);
}
}
And the last one is the main. The thing is that I don't know how can I have more farms and get the max from every single one of them. Can you guys help me?
And this is my mainapp
public class Mainapp {
public static void main(String args[])
{
List <Farm> FarmList = new ArrayList<Farm>();
FarmList.add(new Farm("unirea pizdii", 890030));
FarmList.add(new Farm("pseudo autsm",78594));
FarmList.add(new Farm("haha hihi",854856099));
Farm farm1 = new Farm("Tiguana" , 700);
farm1.makeList("Mihai", 30000);
farm1.makeList("Vladimir", 4000);
farm1.makeList("Tusnic", 3000);
farm1.getList();
Employee emp1 = new Employee(" mihai", 3000);
System.out.println(emp1);
}
}
To get employee with max salary for each farm you can use stream api:
import static java.util.stream.Collectors.*;
Map<Farm, Optional<Employee>> collect =
farmList.stream().collect(groupingBy(Function.identity(),
flatMapping(farm -> farm.getEmployes().stream(),
maxBy(Employee::compareTo))));
Result map has Farm as a key and Employee with max salary as a value
Note: flatMapping method is from java9
There are multiple ways to sort a List in Java, one of them being Collections.sort(List), but in this case it looks like you are trying to retrieve the maximum value from the list, so there's no need to add the extra overhead.
EDIT: JB Nizet suggested using Collections.max(List):
public Employee getMostPaidEmployee() {
return Collections.max(emp);
}
One way to get the most paid employee from the list would be to loop through them and compare each one to the previously "saved" most paid employee:
// Farm.java
public Employee getMostPaidEmployee() {
Employee mostPaid = null;
// Initialize maximum to the lowest possible value.
// If salaries can only be positive you could also initialize this to `0`.
int maximumSalary = Integer.MIN_VALUE;
for (Employee employee : emp) {
if (employee.getSalary() > maximumSalary) {
// Reset the most paid fields
mostPaid = employee;
maximumSalary = employee.getSalary();
}
}
return mostPaid;
}
You can declare this method on the Farm class, so you will be able to call it even if you have multiple instances of Farm:
List<Farm> farms = new ArrayList<>();
// TODO Add farms
// Get the most paid employee in first farm
Employee mostPaid = farms.get(0).getMostPaidEmployee();
In terms of performance, this method is linear, i.e. O(n).

Filtering keys from Map to List attribute in Java 8

I have a List and a Map as below:
public class student {
private String name;
private String age;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
student(String id,String name,String age)
{
}
}
List<student> stulist = Arrays.asList(new student("1", "vishwa",null),
new student("3", "Ravi",null),
new student("2", "Ram",null));
Map<String,String> newmap = new HashMap() {
{
put("1","20");
put("2","30");
}
};
I am comparing like this: If id in map matches the id in list then add
age from Map to age of List.
I have tried this so far , but i am not able to get it.
newmap.entrySet().stream().filter(entry->entry.getKey().equals(student::getId)).collect(..collect here to list..);
stulist = stulist.stream().map(instance -> {
student studentInstance = instance;
studentInstance.setAge(newMap.getOrDefault(studentInstance.getId(),"<default age>"));
return studentInstance;
}).collect(Collectors.toList()); ;
ps: Use proper naming conventions. Change the class name student to Student.
Here is solution, assuming I got the question right:
import java.util.*;
import java.util.stream.*;
public class Answer {
public static void main(String[] args) {
List<Student> studentsWithoutAge = Arrays.asList(
new Student("1", "Vishwa", null),
new Student("3", "Ravi", null),
new Student("2", "Ram", null)
);
Map<String,String> ageById = new HashMap() {{
put("1","20");
put("2","30");
}};
List<Student> studentsWithAge = addAge(studentsWithoutAge, ageById);
System.out.println("Students without age: " + studentsWithoutAge);
System.out.println("Students with age: " + studentsWithAge);
}
static List<Student> addAge(List<Student> students, Map<String,String> ageById) {
return students.stream()
.map(student -> {
String age = ageById.getOrDefault(student.getId(), null);
return new Student(student.getId(), student.getName(), age);
})
.collect(Collectors.toList());
}
}
class Student {
private String name;
private String age;
private String id;
Student(String id,String name,String age){
this.id = id;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public String toString() {
return String.format("Student: id = %s, name = %s, age = %s", this.id, this.name, this.age);
}
}
Implement Student class as #Zgurskyi comment, and then use this on main:
stulist.forEach(stu -> {
stu.setAge(newmap.getOrDefault(stu.getId(), null));
});
Use Collectors.toList()
// Accumulate names into a List
List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());

I want to get individual element of an arrayList in Java

I am newbie in java and I have a method that accepts 3 parameters, query the db and returns result in an arraylist form (like this [1, Java, 3, Bangalore, 10] ). How can i extract individual element so that I can assign each to a var like int id=1;String name=Java.
Below is the method that
ArrayList searchResult =jSearch.doJobSearch(techName, exp, city);
Iterator searchResultIterator = searchResult.iterator();
PrintWriter out = response.getWriter();
String arrayList[] = new String[searchResult.size()];
if(searchResultIterator.hasNext()){
for(int i =0; i<searchResult.size(); i++){
//searchResult.get(i)
out.println(searchResult.get(i));
}
}else{
out.println("No Job found in selected city");
}
ArrayList works in the sense of [index, element].
By using the get method, you're using index as the parameter and it returns the element at that position. So if you're accessing the element by it's index you already have both the id and element, but a different collection interface might suit you better like a map.
http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
Create POJO (Plain Old Java Object). I am providing example how to array list is used when store Real time Object.
package com.appkart.examples;
public class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And Add Employee into Array list and get values
package com.appkart.examples;
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<Employee>();
Employee arun = new Employee(10, "Arun");
Employee ankit = new Employee(20, "Ankit");
Employee jon = new Employee(30, "Jon");
Employee anil = new Employee(40, "Anil");
employees.add(arun);
employees.add(ankit);
employees.add(jon);
employees.add(anil);
for (Employee employee : employees) {
int id = employee.getId();
String name = employee.getName();
System.out.println("id : "+id +" name : "+name);
}
}
}

create new object in arraylist with attributes

I am new to Java and I am starting to work with ArrayLists. What I am trying to do is create an ArrayList for students. Each student has different attribute associated with them (name, id). I am trying to figure out how to add a new student object with this attributes. Here is what I have:
ArrayList < Student > studentArray;
public Student(String name, int id) {
this.fname = name;
this.stId = id;
}
public Stromg getName() {
return fname;
}
public int getId() {
return stId;
}
public boolean setName(String name) {
this.fname = name;
return true;
}
public boolean setIdNum(int id) {
this.stId = id;
return true;
}
What you need is something like the following:
import java.util.*;
class TestStudent
{
public static void main(String args[])
{
List<Student> StudentList= new ArrayList<Student>();
Student tempStudent = new Student();
tempStudent.setName("Rey");
tempStudent.setIdNum(619);
StudentList.add(tempStudent);
System.out.println(StudentList.get(0).getName()+", "+StudentList.get(0).getId());
}
}
class Student
{
private String fname;
private int stId;
public String getName()
{
return this.fname;
}
public int getId()
{
return this.stId;
}
public boolean setName(String name)
{
this.fname = name;
return true;
}
public boolean setIdNum(int id)
{
this.stId = id;
return true;
}
}
You instantiate a Student object by passing the appropriate values to the constructor.
Student s = new Student("Mr. Big", 31);
You place elements into an ArrayList (or List) by using the .add() operator.*
List<Student> studentList = new ArrayList<Student>();
studentList.add(s);
You retrieve user input via the use of a Scanner bound to System.in.
Scanner scan = new Scanner(System.in);
System.out.println("What is the student's name?");
String name = scan.nextLine();
System.out.println("What is their ID?");
int id = scan.nextInt();
You repeat this with a loop. That portion shall be left as an exercise to the reader.
*: There are other options, but add() simply adds it to the end, which is typically what you want.
final List<Student> students = new ArrayList<Student>();
students.add(new Student("Somename", 1));
... and so on add more students

Categories

Resources