Generating sequence numbers in Java from the ArrayList - java

How to generate sequence numbers and assign them to each object in java?
for example i have the following,
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class MyMaxUDOComparable
{
public static Integer findMaxScore(List<testVO> emps)
{
Integer maxScoreTotal = 0;
for (Iterator<JobFitSurveyConfigVO> iterator = emps.iterator(); iterator.hasNext();)
{
testVOempl = (testVO) iterator.next();
if (empl != null)
{
maxScoreTotal += empl.getSalary();
}
}
return maxScoreTotal;
}
public static void main(String a[])
{
List<testVO> emps = new ArrayList<testVO>();
emps.add(new testVO(10, "Raghu", 10,1));
emps.add(new testVO(120, "Krish", 10,2));
emps.add(new testVO(210, "John", 10,3));
emps.add(new testVO(150, "Kishore", 10,4));
testVOmaxSal = Collections.max(emps);
System.out.println("Employee with max Id: " + maxSal);
System.out.println("maxScoreTotal: " + findMaxScore(emps));
}
}
class testVOimplements Comparable<testVO>
{
private Integer id;
private String name;
private Integer salary;
private Integer sequenceNumber;
public testVO(Integer id, String name, Integer sal,Integer sequenceNumber) {
this.id = id;
this.name = name;
this.salary = sal;
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Integer getSalary()
{
return salary;
}
public void setSalary(Integer salary)
{
this.salary = salary;
}
public Integer getSequenceNumber()
{
return sequenceNumber;
}
public void setSequenceNumber(Integer sequenceNumber)
{
this.sequenceNumber = sequenceNumber;
}
#Override
public int compareTo(JobFitSurveyConfigVO emp)
{
return this.id.compareTo(emp.getId());
}
public String toString()
{
return id + " " + name + " " + salary;
}
}
in the above class, i have assigned values to all the objects for Sequence Number and if I remove any object from the list then the Sequence Number has to be re generated.
how to do this in java, would some one help me on this please?.

public void deleteObjFormList(JobFitSurveyConfigVO emp,List<JobFitSurveyConfigVO> emps)
{
int i = emps.indexOf(emp);
emps.remove(i);
for(int j=i;j<emps.size();j++)
{
JobFitSurveyConfigVO emp1 = emps.get(j);
emp1.setSequenceNumber(emp1.getSequenceNumber()-1);
}
return;
}
I this this should be a function to remove the object from the list.

You iterate the list and set the sequence number.
Be aware that your constructor is not assigning the sequence number, so although you provided values, they are all null. If you changed type to the more sensible int, they would be 0.
// Renumber (aka resequence) the emp records
for (int i = 0; i < emps.size(); i++)
emps.get(i).setSequenceNumber(i + 1);

try this way
public static void main(String a[]) {
List<JobFitSurveyConfigVO> emps = new ArrayList<JobFitSurveyConfigVO>();
ArrayList<Integer> seq = new ArrayList<Integer>();
addElement(seq, emps, 10, "Raghu", 10);
addElement(seq, emps, 120, "Krish", 10);
addElement(seq, emps, 210, "John", 10);
addElement(seq, emps, 150, "Kishore", 10);
System.out.println("Display : "+emps);
removeElement(2, seq, emps);
System.out.println("Removed : "+emps);
addElement(seq, emps, 210, "John2", 10);
System.out.println("Added : "+emps);
}
Add Element and Remove Element methods
public static void addElement(ArrayList<Integer> seq,
List<JobFitSurveyConfigVO> emps, int id, String name, Integer salary) {
int size = seq.size();
Collections.sort(seq); // Make sure they are in Sequence.
if (size > 1) {
for (int i = 1; i < size; i++) {
int check = seq.get(i-1);
if ( (check + 1) != (seq.get(i))) {
seq.add(check + 1);
emps.add(new JobFitSurveyConfigVO(id, name, salary, (check + 1)));
break;
}
if (i+1 == size) {
seq.add(seq.get(i) + 1);
emps.add(new JobFitSurveyConfigVO(id, name, salary, (seq.get(i) + 1)));
}
}
}else if (size == 1 && seq.get(0) == 1) {
int check = seq.get(0);
seq.add(check + 1);
emps.add(new JobFitSurveyConfigVO(id, name, salary, (check + 1)));
}else{
seq.add(1);
emps.add(new JobFitSurveyConfigVO(id, name, salary, 1));
}
}
public static void removeElement(int index, ArrayList<Integer> seq, List<JobFitSurveyConfigVO> emps){
if (index < seq.size()) {
emps.remove(index);
seq.remove(index);
}else {
throw new ArrayIndexOutOfBoundsException();
}
}
constructor
public JobFitSurveyConfigVO(Integer id, String name, Integer sal,Integer sequenceNumber) {
this.id = id;
this.name = name;
this.salary = sal;
this.sequenceNumber = sequenceNumber;
}

Related

Iterate List based on condition Set Values to another object

Iterate List based on condition Set Values to another object using Java 8?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Demo {
public static void main(String[] args) {
// TODO: Condition is => Only if id = 100, then assign internalMarks to (externalMarks + internalMarks); to 103
// So internalMarks = 0 and externalMarks = 500+250=750
List<Employee> employees = Arrays.asList(
new Employee(100, 500, "John", 250),
new Employee(101, 500, "Jane", 250),
new Employee(102, 500, "Jack", 250),
new Employee(103, 500, "Mike", 250)
);
List<Employee> newList = new ArrayList<>();
employees.stream().forEach(e -> {
if(e.getId() == 100 && e.getId() > 0) {
e.setExternalMark(0);
newList.add(e);
}else {
newList.add(e);
}
});
System.out.println(newList);
}
static class Employee {
private int id;
private int internalMark;
private String name;
private int externalMark;
public Employee() {
}
public Employee(int id, int internalMark, String name, int externalMark) {
super();
this.id = id;
this.internalMark = internalMark;
this.name = name;
this.externalMark = externalMark;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getInternalMark() {
return internalMark;
}
public void setInternalMark(int internalMark) {
this.internalMark = internalMark;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getExternalMark() {
return externalMark;
}
public void setExternalMark(int externalMark) {
this.externalMark = externalMark;
}
#Override
public String toString() {
return "Employee [id=" + id + ", internalMark=" + internalMark + ", name=" + name + ", externalMark="
+ externalMark + "]";
}
}
}
//Condition is => Only if id = 100, then assign internalMarks to (externalMarks + internalMarks); to 103
// So internalMarks = 0 and externalMarks = 500+250=750
From your condition, as its slighlty unclear that externalMarks should be changes for Id=100 or Ids 100 to 103, means for all Employees
Take one scenario, where externalMarks should be changes for id = 100, then solution can be
List<Employee> newList1 = employees.stream()
.map(e-> {
if(e.getId() == 100) {
e.setExternalMark(e.getInternalMark()+e.getExternalMark());
e.setInternalMark(0);
}
return e;
})
.collect(Collectors.toList());
For other scenario, where externalMarks should be changes for id = 100 to 103, then solution can be
List<Employee> newList1 = employees.stream()
.map(e-> {
e.setExternalMark(e.getInternalMark()+e.getExternalMark());
e.setInternalMark(0);
return e;
})
.collect(Collectors.toList());

Compare Duplicate Data From a List with Inputed Data

I want to check duplicate IDs from a list with the data I inputted, then increment the qty variable in the list. If it's new data, it will add a new list.
This is my code
public void addBarang(Barang barang){
int id_barang = barang.getId();
if(this.list.isEmpty())
{
list.add(barang);
}
else
{
for(int i=0;i<list.size();i++)
{
if(list.get(i).getId() != id_barang)
{
list.add(barang);
System.out.println("Added");
break;
}
if(list.get(i).getId() == id_barang)
{
int new_qty = list.get(i).getQty()+barang.getQty();
list.get(i).setQty(new_qty);
}
}
}
}
Even if I input new data it always increments the qty of old data and the new data is not added (basically always end in the "else" section).
Code for inputing data
Gudang gudang1 = new Gudang(1,1);
System.out.println("ID: ");
int id = input.nextInt();
System.out.println("Jumlah: ");
int qty = input.nextInt();
System.out.println("Nama: ");
String name = input.next();
Barang barang = new Barang(id,name,qty);
gudang1.addBarang(barang);
Barang Class
public class Barang {
public static int id;
private String name;
private int qty;
public Barang(int id, String name, int qty) {
this.id = id;
this.name = name;
this.qty = qty;
}
public Barang(){
};
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getQty() {
return qty;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setQty(int qty) {
this.qty = qty;
}
#Override
public String toString() {
return "Barang{" + "id=" + id + ", name=" + name + ", qty=" + qty + '}';
}
Gudang Class
public class Gudang {
public static int id;
private int location;
public List<Barang> list = new ArrayList<Barang>();
public Gudang(int id, int location) {
Gudang.id = id;
this.location = location;
}
public int getId() {
return id;
}
public int getLocation() {
return location;
}
public List<Barang> getList() {
return list;
}
public void setId(int id) {
this.id = id;
}
public void setLocation(int location) {
this.location = location;
}
public void setList(List<Barang> list) {
this.list = list;
}
public void addBarang(Barang barang){
int id_barang = barang.getId();
if(this.list.isEmpty())
{
list.add(barang);
}
else
{
for(int i=0;i<list.size();i++)
{
if(list.get(i).getId() != id_barang)
{
list.add(barang);
System.out.println("Added");
break;
}
if(list.get(i).getId() == id_barang)
{
int new_qty = list.get(i).getQty()+barang.getQty();
list.get(i).setQty(new_qty);
}
}
}
System.out.println("Size List = "+list.size());
}
public void duplicate(List<Barang> list2)
{
this.list.addAll(list2);
}
public void clearBarang(){
this.list.clear();
}
public void display(){
for(Barang barang: this.list){
System.out.println(barang);
}
}
IE : If I have id=1 and qty=1, then input a new data with id=2 and qty=2, the final result will end up with id=2 and qty=3. No new data int he list were added.
try using .equals to compare if the data exist in your list
Please check if ids are duplicate between your old and new data.
If you ids are unique then you can take advantage of Map and put id as key and barang object as value. Whenever you successfully lookup map increment quantity field of object.
At first guess i would change:
if(list.get(i).getId() != id_barang)
to:
if(list.get(i).getId() != barang.getId())
maybe id_barang is not the same as the id stored in the barang object.

Sort ArrayList of objects by field in custom order

How can I achieve a custom sorting to the content of field name:
first element: P followed by numbers [1-9]{2} always on first
followed by : P followed by numbers 0[0-9]
followed by : S
followed by numbers [1-9]{2}
and then the rest in normal order i1.getName().compareToIgnoreCase(i2.getName())
private static Comparator<Item> itemComperator = new Comparator<Item>() {
#Override
public int compare(Item i1, Item i2) {
if (i1.getName().matches("P[1-9]{2}") && i2.getName().matches("P0[0-9]"))
return -1;
else if (i1.getName().matches("S[1-9]{2}"))
return -1;
else
return i1.getName().compareToIgnoreCase(i2.getName());
}
};
#Test
public void sortItem() {
Item item01 = new Item(1, "R59");
Item item02 = new Item(2, "S48");
Item item03 = new Item(3, "P01");
Item item04 = new Item(4, "P25");
Item item05 = new Item(5, "R99");
List<Item> items = Arrays.asList(item01, item02, item03, item04, item05);
System.out.println("before sorting");
long seed = System.nanoTime();
Collections.shuffle(items, new Random(seed));
for (Item i : items) {
System.out.println(i.getId() + " " + i.getName());
}
System.out.println("after sorting");
Collections.sort(items, itemComperator);
for (Item i : items) {
System.out.println(i.getId() + " " + i.getName());
}
}
public class Item {
private int id;
private String name;
public Item(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;
}
}
output expected:
after sorting
4 P25
3 P01
2 S48
1 R59
5 R99
I think that I would first map each of the inputs to a "kind" number, which is based upon the list of criteria above. For example:
int kind(String input) {
if (input.matches("P[1-9]{2}") {
return 0;
} else if (input.matches("P0[0-9]")) {
return 1;
} else if (input.matches("S.*")) {
return 2;
} else if (input.matches("[1-9]{2}")) {
return 3;
} else {
return 4;
}
}
This gives you a way to see if the two strings are of the same "kind"; if not, return the ordering based on the kind. If they are the same kind, just compare them using (case insensitive) lexicographic ordering (you don't specify, but I assume you want e.g. "P11" to come before "P22"):
public int compare(Item a, Item b) {
String nameA = a.getName();
String nameB = b.getName();
int kindA = kind(nameA);
int kindB = kind(nameB);
if (kindA != kindB) {
return Integer.compare(kindA, kindB);
} else {
return nameA.compareToIgnoreCase(nameB);
}
}

Create an array by passing the txt file and Pass array reference variable to the heapsort method

I need help with my project for data structure course. I am suppose to read 10 employees data stored in a text file called Employee.txt and read them into an array then pass that array into the heapSort method and print the sorted employees into an output file called SortedEmployee.txt. For some reason my program is not working. Can anyone help please?
Class Employee
import java.util.ArrayList;
public class Employee
{
public String empId , empName , empDept , empPos;
public double empSalary;
public int empServ;
Employee()
{
empId = ("");
empName = ("");
empDept = ("");
empPos = ("");
empSalary = 0.0;
empServ = 0;
}
Employee(String id ,String name, double salary, String dept , String pos, int serv)
{
empId = id;
empName = name;
empDept = dept;
empPos = pos;
empSalary = salary;
empServ = serv;
}
public void setId(String id)
{
empId = id;
}
public void setName(String name)
{
empName = name;
}
public void setDept(String dept)
{
empDept = dept;
}
public void setPos(String pos)
{
empPos = pos;
}
public void setSalary(double salary)
{
empSalary = salary;
}
public void setServ(int serv)
{
empServ = serv;
}
public String getId()
{
return empId;
}
public String getName()
{
return empName;
}
public String getDept()
{
return empDept;
}
public String getPos()
{
return empPos;
}
public double getSalary()
{
return empSalary;
}
public int getServ()
{
return empServ;
}
public String toString()
{
String str = "Employee Name : " + empName + "\nEmployee ID : " + empId +
"\nEmployee Deaprtment : " + empDept + "\nEmployee Position : "
+ empPos + "\nEmployee Salary : " + empSalary
+ "\nEmployee Years Served : " + empServ;
return str;
}
public int compareTo(Employee emp)
{
int id = empId.compareToIgnoreCase(emp.empId);
if (id != 0)
return id;
return 0;
}
}
Class HeapSort
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
class zNode
{
private int iData;
public zNode(int key)
{
iData = key;
}
public int getKey()
{
return iData;
}
public void setKey(int k)
{
iData = k;
}
}
class HeapSort
{
private int [] currArray;
private int maxSize;
private int currentSize;
private int currIndex;
HeapSort(int mx)
{
maxSize = mx;
currentSize = 0;
currArray = new int[maxSize];
}
//buildheap
public boolean buildHeap(int [] currArray)
{
int key = currIndex;
if(currentSize==maxSize)
return false;
int newNode = key;
currArray[currentSize] = newNode;
siftUp(currArray , currentSize++);
return true;
}
//siftup
public void siftUp(int [] currArray , int currIndex)
{
int parent = (currIndex-1) / 2;
int bottom = currArray[currIndex];
while( currIndex > 0 && currArray[parent] < bottom )
{
currArray[currIndex] = currArray[parent];
currIndex = parent;
parent = (parent-1) / 2;
}
currArray[currIndex] = bottom;
}
//siftdown
public void siftDown(int [] currArray , int currIndex)
{
int largerChild;
int top = currArray[currIndex];
while(currIndex < currentSize/2)
{
int leftChild = 2*currIndex+1;
int rightChild = leftChild+1;
if(rightChild < currentSize && currArray[leftChild] < currArray[rightChild] )
largerChild = rightChild;
else
largerChild = leftChild;
if( top >= currArray[largerChild] )
break;
currArray[currIndex] = currArray[largerChild];
currIndex = largerChild;
}
currArray[currIndex] = top;
}
//remove max element
public int removeMaxElement(int [] currArray)
{
int root = currArray[0];
currArray[0] = currArray[--currentSize];
siftDown(currArray , 0);
return root;
}
//heapsort
private void _sortHeapArray(int [] currArray)
{
while(currentSize != 0)
{
removeMaxElement(currArray);
}
}
public void sortHeapArray()
{
_sortHeapArray(currArray);
}
//hepify
private int[] heapify(int[] currArray)
{
int start = (currentSize) / 2;
while (start >= 0)
{
siftDown(currArray, start);
start--;
}
return currArray;
}
//swap
private int[] swap(int[] currArray, int index1, int index2)
{
int swap = currArray[index1];
currArray[index1] = currArray[index2];
currArray[index2] = swap;
return currArray;
}
//heapsort
public int[] _heapSort(int[] currArray)
{
heapify(currArray);
int end = currentSize-1;
while (end > 0)
{
currArray = swap(currArray,0, end);
end--;
siftDown(currArray, end);
}
return currArray;
}
public void heapSort()
{
_heapSort(currArray);
}
//main method
public static void main (String [] args) throws IOException
{
HeapSort mySort = new HeapSort(10);
Employee [] myArray = new Employee[10];
String firstFile = ("Employee.txt");
FileReader file = new FileReader(firstFile);
BufferedReader br = new BufferedReader(file);
String secondFile = ("SortedEmployee.txt");
PrintWriter outputFile = new PrintWriter(secondFile);
String[] currArray = new String[10];
String lineContent;
while ((lineContent = br.readLine()) != null)
{
for (int i = 0; i < currArray.length; i++)
{
lineContent = br.readLine();
currArray[i] = String.valueOf(lineContent);
mySort.heapSort();
outputFile.println(mySort);
}
}
outputFile.close();
System.out.print("Done");
}
}
I know that the problem is in the main method in the while loop but I just don't know how to solve it.
Employee.txt:
086244
Sally L. Smith
100000.00
Accounting
Manager
7
096586
Meredith T. Grey
150000.00
Physical Therapy
Doctor
9
875236
Christina R. Yang
190000.00
Cardiology
Resident
10
265893
George A. O'Malley
98000.00
Pediatrics
Attending
7
etc......
You have not implemented Comparable<Employee>. It should like this.
public class Employee implements Comparable<Employee>{
#Override
public int compareTo(Employee emp){
return this.empId.compareToIgnoreCase(emp.empId);
}
}
Simply use Arrays.sort() method to sort an array.

input from Keyboard into Array list of persons

I want to accept input from user to populate an Array list of Person. for some reason. I can't get it to work. I can add an item into the list I have created below are my code for reference. in the SimplepersonDatabase class in switch function case 2:, I want to accept an an input of names, date of birth from the user and the program should automatically assign the position number starting from
e.g
001. Damien Kluk September, 12.09.1975
002. James Hunt January , 12.09.2000
I should be able to also delete a person and sort the list of Persons. here are what I have implemented so far.
public class Person { //Person.java
public String fn;
public String ln;
public Date dob;
public int id;
public Person() {
}
public Person(String fn, String ln, Date dob, int id) {
this.fn = fn;
this.ln = ln;
this.dob = dob;
this.id = id;
}
}
class List {//List.java
int MAX_LIST = 20;
Person[] persons;
int count;
public List() {
persons = new Person[MAX_LIST];
count=0;
}
public int numberOfPersons() {
return count;
}
public void add(Person person) {
checkUniqueId(person);
if (count >= persons.length) {
// Enlarge array
persons = Arrays.copyOf(persons, persons.length + 100);
}
persons[count] = person;
++count;
}
private void checkUniqueId(Person person) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == person.id) {
throw new IllegalArgumentException("Already a person with id "
+ person.id);
}
}
}
public void remove(int personId) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == personId) {
--count;
persons[i] = persons[count];
persons[count] = null;
return;
}
}
throw new IllegalArgumentException("No person known with id "
+ personId);
}
}
public class SimplePersonDataBase { //SimplePersonDataBase.java
private static List list;
private static int nextPersonId;
public static void main(String[] args) {
go();
}
public static void go() {
List link = new List();
TextIO.put("Welcome to the SimplePersonDatabase.\n");
TextIO.putln();
int option;
do{
TextIO.put("available options:\n1) list\n2) add\n3) remove\n4) sort\n5) find\n6) settings\n0) quit\nyour choice:");
option = TextIO.getInt();
switch(option){
case 1:
PersonFunctions.display();
break;
case 2: // Should accept inputs from a user and update the Persons database
TextIO.put("Firstname:");
String fn = TextIO.getlnWord();
TextIO.put("Lastname:");
String ln = TextIO.getlnWord();
Date date = DateFunctions.scanDate();
int pos = link.count;
Person item = new Person(fn,ln,date,pos);
add(item);
break;
case 3:
break;
case 4:
TextIO.putln("sort by:\n1) Firstname\n2) Birth\nall other values: lastname");
switch(TextIO.getInt()){
case 1:
break;
case 2:
break;
default :
break;
}
break;
case 5:
break;
case 6:
break;
case 0:
TextIO.put("Thank you for using the SimplePersonDatabase.");
break;
case 99:
break;
default :
TextIO.put("illegal option.");
break;
}
}while(option !=0);
}
public static boolean add(Person personadd) {
personadd.id = nextPersonId;
++nextPersonId;
list.add(personadd);
return true;
}
}
Your list is working well (I tried + or -)
import java.util.Arrays;
import java.util.Date;
class Person { // Person.java
public String fn;
public String ln;
public Date dob;
public int id;
public Person() {
}
public Person(String fn, String ln, Date dob, int id) {
this.fn = fn;
this.ln = ln;
this.dob = dob;
this.id = id;
}
}
the list
public class MyList {
int MAX_LIST = 20;
Person[] persons;
int count;
public MyList() {
persons = new Person[MAX_LIST];
count = 0;
}
public int numberOfPersons() {
return count;
}
public void add(Person person) {
checkUniqueId(person);
if (count >= persons.length) {
// Enlarge array
System.out.println("enlarging");
persons = Arrays.copyOf(persons, persons.length + 100);
}
persons[count] = person;
++count;
}
private void checkUniqueId(Person person) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == person.id) {
throw new IllegalArgumentException("Already a person with id "
+ person.id);
}
}
}
public void remove(int personId) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == personId) {
--count;
persons[i] = persons[count];
persons[count] = null;
return;
}
}
throw new IllegalArgumentException("No person known with id "
+ personId);
}
public Person get(int i) {
return persons[i];
}
public static void main(String[] args) {
MyList list = new MyList();
for (int i=0; i<1000; i++) {
list.add(new Person("fn"+i,"sn"+i,new Date(),i));
System.out.println(list.get(i) + " " + list.count);
}
}
}
the problem is in the "go" function, why you are using link and then you add in list?

Categories