'Task1:Search for people with their social security number. Task 2: Fetch the list of residents based on their gender
I've created an ArrayList
of Residents
. Each Residents
consists of full name, ssn number and gender. I had to sort the elements by ssn
number first and then by their full name (not a single sorting by two fields, but two distinct sorts). However, I don't know how to search for people according to their ssn
, can anyone help me with this?
In my code, I've written “enter ssn number” twice because I've tried different ways, but I've got the wrong output. if I enter 100 as ssn number, I should get only “srinivas”. The first time I am getting ["srinivas", 100,"Male"]
but the second time I'm getting the wrong output.
package ResidentSearch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ListIterator;
import java.util.Scanner;
import java.util.function.Predicate;
public class HospitalMain {
public static void main(String[] args) {
Residents res1 = new Residents("srinivas", 100, "Male");
Residents res2 = new Residents("bunny", 200, "Female");
Residents res3 = new Residents("sunny", 400, "Female");
Residents res4 = new Residents("chinny", 300, "Male");
ArrayList<Residents> resDetails = new ArrayList<Residents>();
resDetails.add(res1);
resDetails.add(res2);
resDetails.add(res3);
resDetails.add(res4);
System.out.println("Residents details are here....\n");
System.out.println(resDetails);
/*ListIterator ltr = resDetails.listIterator();
while (ltr.hasNext()) {
System.out.println(ltr.next());
}*/
Collections.sort(resDetails, (e1, e2) -> (e1.getSsn() < e2.getSsn()) ? -1 : (e1.getSsn() > e2.getSsn()) ? 1 : 0);
System.out.println("\nResidents details are here according to ssn number....\n");
ListIterator ltr1 = resDetails.listIterator();
while (ltr1.hasNext()) {
System.out.println(ltr1.next());
}
Collections.sort(resDetails, (e1, e2) -> (e1.getFullName().compareTo(e2.getFullName())));
System.out.println("\nResidents details are here according to name ....\n");
ListIterator ltr2 = resDetails.listIterator();
while (ltr2.hasNext()) {
System.out.println(ltr2.next());
}
System.out.println("\nsearch by name or ssn number or gender:\n");
System.out.println("Enter any ssn number:");
Scanner sc = new Scanner(System.in);
String s = sc.next();
int count = 0;
//Collections.sort(resDetails,new ssnCompare());
ListIterator ltr3 = resDetails.listIterator();
while (ltr3.hasNext()) {
Residents ss = (Residents) ltr3.next();
if ((ss.toString()).contains(s)) {
System.out.println(ss);
} else {
count++;
}
}
if (count > 3)
System.out.println("sorry.. entered ssn number is not availble.");
//ListIterator ltr4 = resDetails.listIterator();
System.out.println("enter any ssn number:");
Predicate<Residents> p = rD -> rD.getSsn() == sc.nextInt();
for (Residents rd : resDetails) {
if (p.test(rd)) {
System.out.println(rd.getFullName());
}
}
/*while (ltr4.hasNext()) {
if (ltr4.next().toString().contains((sc.nextInt() + ""))) {
String s1 = ((Residents) ltr4.next()).getFullName();
//Residents s2 = (Residents) ltr4.previous();
System.out.println(s1);
}
}*/
//System.out.println(Collections.binarySearch(resDetails,"srinivas"));
}
}
Solution 1:[1]
After reading your comments I think I better understand now what you need.
First of all, since you're doing many sorting or search operations on the ssn
field, I would suggest you to implement the Comparable
interface on your Residents
class and define a natural ordering for it. The other type of ordering, like by name, can be achieved by simply passing a custom Comparator
.
In the code below, I'm pitching you two different ways of looking for an element. You don't need to use both, just keep the one that fits you the most. The first one uses collection streams, while the other the binary search algorithm since you were asking about it in the comments.
Here is my implementation of your solution.
Residents
public class Residents implements Comparable<Residents> {
private String fullName;
private int ssn;
private String gender;
//... constructor ...
//... getters and setters ...
@Override
//Implementing the compareTo method to define a natural ordering by ssn number
public int compareTo(Residents other) {
//Instancing a new int comparator and applying it on the current object (this) and the paramter (other)
return Comparator.comparingInt(Residents::getSsn).compare(this, other);
}
@Override
public String toString() {
return String.format("%s %d %s", fullName, ssn, gender);
}
}
Main
package ResidentSearch;
import java.util.*;
class HospitalMain {
public static void main(String[] args) {
Residents res1 = new Residents("srinivas", 100, "Male");
Residents res2 = new Residents("bunny", 200, "Female");
Residents res3 = new Residents("sunny", 400, "Female");
Residents res4 = new Residents("chinny", 300, "Male");
List<Residents> listResidents = new ArrayList<>();
listResidents.add(res1);
listResidents.add(res2);
listResidents.add(res3);
listResidents.add(res4);
System.out.println("Residents details are here....");
System.out.println(listResidents);
System.out.println("\nResidents details ordered by ssn number....");
// Sorting Residents elements with via their natural ordering (ssn number).
// The natural ordering refers to the order defined by implementing the Comparable interface.
Collections.sort(listResidents);
System.out.println(listResidents);
System.out.println("\nResidents details are here according to name....");
// Sorting by the sort method of the List interface and providing an alternative ordering with a Comparator instance which orders Residents by fullName
listResidents.sort(Comparator.comparing(Residents::getFullName));
System.out.println(listResidents);
Scanner sc = new Scanner(System.in);
System.out.println("\nSearch by ssn number");
System.out.print("Enter a ssn number: ");
//Showing an error message and requesting the ssn number as long as the user does not insert a number
while (!sc.hasNextInt()) {
//NextLine() call to discard the wrong user input
sc.nextLine();
System.out.println("Enter a valid ssn number!");
System.out.print("Enter a ssn number: ");
}
int ssn = sc.nextInt();
//Streaming the list of residents and filtering for the ssn inserted by the user.
// The terminal operation findFirst gets the first and only result,
// while the orElse method returns the only Resident or null if there is no resident with the ssn inserted by the user
Residents residentResult = listResidents.stream()
.filter(r -> r.getSsn() == ssn)
.findFirst()
.orElse(null);
//Printing the result
System.out.println("\nPrinting the result via stream research");
if (residentResult != null) {
System.out.printf("Resident with %d ssn number is: %s%n", ssn, residentResult.getFullName());
} else {
System.out.printf("There is no resident with %d ssn number...%n", ssn);
}
//An alternative way to look for a resident with the inserted ssn number is via the binarySearch method of the Collections class.
//In order to search by ssn number though, we first need to sort the list by ssn number.
//Then, we need to pass a Resident with the same information used in the compareTo method,
//in order to match them when they both have the same ssn number.
Collections.sort(listResidents);
int index = Collections.binarySearch(listResidents, new Residents("", ssn, ""));
//Printing the result
System.out.println("\nPrinting the result via binary search");
if (index >= 0) {
System.out.printf("Resident with %d ssn number is: %s%n", ssn, listResidents.get(index).getFullName());
} else {
System.out.printf("There is no resident with %d ssn number...%n", ssn);
}
}
}
Side Note
As a standard practice, classes should have singular names, not plural. So, it would be better if your Residents
class was named Resident
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |