how to implement Custom Auto suggestion in java like google - java

how to implement Java Based Auto suggestion. suppose I have different types of data like firstName, rollNumber, address.
My first requirement is like if user enter first character on text box, then result should be sorted on natural order based on firstName and 10 results should be display.
after space if use enter second character and if it is numbere then RollNumber else lastName should be sorted on natural order as ascending.
or if user type third character then Address should be display on ascending order. there should be no database, you don't have to implement Solr or other api. how to implement on pure Java.
here I did not implement the text-box,but I Just took an example to demonstrate
import java.util.*;
import java.lang.*;
import java.io.*;
// A class to represent a student.
class Student {
int rollno;
String name;
String address;
// Constructor
public Student(int rollno, String name, String address) {
this.rollno = rollno;
this.name = name;
this.address = address;
}
// Used to print student details in main()
public String toString(){
return this.rollno + " " + this.name +
" " + this.address;
}
}
class Sortbyroll implements Comparator<Student> {
// Used for sorting in ascending order of rollno
public int compare(Student a, Student b) {
return a.rollno - b.rollno;
}
}
class Sortbyname implements Comparator<Student> {
// Used for sorting in ascending order of name
public int compare(Student a, Student b) {
return a.name.compareTo(b.name);
}
}
// Driver class
class Main {
public static void main (String[] args) {
ArrayList<Student> ar = new ArrayList<Student>();
//here I have thousand student are inserted into
//simple collection.
ar.add(new Student(111, "bbbb", "london"));
ar.add(new Student(131, "aaaa", "nyc"));
ar.add(new Student(121, "cccc", "jaipur"));
System.out.println("Unsorted");
for (int i=0; i<ar.size(); i++) {
System.out.println(ar.get(i));
}
//collection sorted by rollno
Collections.sort(ar, new Sortbyroll());
System.out.println("\nSorted by rollno");
for (int i=0; i<ar.size(); i++) {
System.out.println(ar.get(i));
}
//sort by Name
Collections.sort(ar, new Sortbyname());
System.out.println("\nSorted by name");
for (int i=0; i<ar.size(); i++) {
System.out.println(ar.get(i));
}
}
}

First of all your question is incomplete and misleading. It does not describes the requirement properly. But overall what I assume
You want Google like (?) suggester in your text box
It does not tell any specific things. What about your front end ? How about your data ?
Any way I think you just wanted to have a console like application where you will give partial String as input and your method will guess the Rest of String as an assumption from your dummy data. Am I right ?
If that is the thing you were looking for then I just sketched a demo code below
static List<String> query(String queryStr, List<Student> list) {
List<String> suggestion = new ArrayList<>();
list.forEach(std -> {
if (isMatched(queryStr, String.valueOf(std.getRoll()))) {
suggestion.add(String.valueOf(std.getRoll()));
}
if (isMatched(queryStr, std.getName())) {
suggestion.add(std.getName());
}
if (isMatched(queryStr, std.getAddress())) {
suggestion.add(std.getAddress());
}
});
return suggestion;
}
private static boolean isMatched(String query, String text) {
return text.toLowerCase().contains(query.toLowerCase());
}
And what does this code do ? It actually takes the Partial String that the user input so far and your List<Student> as parameters. Then it iterates over the list and matches for all field for partial match. If any field matches the query it add that value in the suggestion list. In the main you can do like this :
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(101, "Abc ghi", "USA"));
list.add(new Student(102, "DEF", "UST"));
list.add(new Student(103, "Ghi ab", "DSjkD"));
list.add(new Student(104, "jKL ut", "USN"));
list.add(new Student(105, "MNP", "TSA101"));
list.add(new Student(106, "UTC ABC", "ESA"));
List<String> sugg = query("01", list);
sugg.forEach(System.out::println);
}
and you will find the console printed like :
101
TSA101
Does it make sense ? it might not be your whole confusing requirements. But I think you got the idea. You can exploit this to address your own requirements. You could further imply your sorting logic or any kind of filters to it. It should not be that tough thing.
But you should be concerned that with large number of collection or complex associated objects this would not suffice. Real world application does not work this straight forward. You might need lot of other things to consider like memory, i/o and execution time.
Good Luck!

Do refer https://github.com/nikcomestotalk/autosuggest/
This implementation is in java based on Patricia trie and Edit distance algorithm.
Some salient features of this application is
Auto correction of keywords
Bucket support for sorting and personalization support.
Filtering support.
Limit support.
Build in http server.
Blazing fast search.
And you all are welcome for feedback
Solr/Lucene/Elastic will not give freedom to choose algorithm and personalization support.

You can use a Trie data structure for autosuggestion implementation and the time complexity would be O(word_length) for insert and search.
Apache commons provides implementation "org.apache.commons.collections4.Trie"
example:
Trie<String, String> trie = new PatriciaTrie<>();
trie.put("abcd", "abcd");
trie.put("abc", "abc");
trie.put("abef", "abef");
SortedMap<String, String> map = trie.prefixMap("ab");
map.forEach((k, v) -> {
System.out.println(k + " " + v);
});

Related

Why does adding "|" to Set in Java flip the elements order?

I have two Lists and trying to form a String with element from each List, and in between when I do " ", the sorted order is maintained. But once I put "|" in the middle, which I would want to, the order of the elements in the Set gets switched around.
How can I add "|" and still maintain the sorted order in the Set students?
Here is the code:
Set<String> students = new HashSet<>();
Set<String> fn = new HashSet<>();
Set<String> nums = new HashSet<>();
List<String> firstNames = new ArrayList<>(fn);
Collections.sort(firstNames);
List<String> favNumbers = new ArrayList<>(nums);
Collections.sort(favNumbers);
for(int i=0; i<firstNames.size(); i++) {
students.add(firstNames.get(i) + "|" + favNumbers.get(i));
}
System.out.println(students);
With ... + " " + ..., the order is [Joshua 4, Lyon 7], but if "|" is added in place of " ", the order becomes [Lyon|7, Joshua|4] when I want and should be[Joshua|4, Lyon|7].
A HashSet does not provide any ordering guarantees about its contents, using whatever ordering the underlying HashMap generates, which is in turn based on the hashCode() of the elements.
When you change the contents of a string, you get a different hash code--simple as that. The order in a HashMap is undefined and could change if you inserted additional elements triggering a rehash.
If you want a set with a guaranteed order, you can use a SortedSet implementation (such as TreeSet), but you'd need to write a proper class and implement suitable Comparators. Alternately, you could use LinkedHashSet, which maintains elements in insertion order at the expense of additional overhead.
You should be using object oriented design, as Java is an object oriented language. Instead of trying to represent the various features of a student as independent collection, create a Student POJO which contains these features. Then, create custom comparators to sort by either name or favorite number.
public class Student {
private String firstName;
private String lastName;
private int favNumber;
// getters and setters
public static Comparator<Student> NameComparator
= new Comparator<Student>() {
public int compare(Student s1, Student s2) {
String f1 = s1.getFirstName();
String f2 = s2.getFirstName();
String l1 = s1.getLastName();
String l2 = s2.getLastName();
if (l1.equalsIgnoreCase(l2) {
return f1.toUpperCase().compareTo(f2);
}
else {
return l1.toUpperCase().compareTo(l2);
}
}
};
public static Comparator<Student> FavComparator
= new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getFavNumber() < s2.getFavNumber();
}
};
}
Now if you have a list of students, List<Student> list, you can sort via:
Collections.sort(list, Student.NameComparator);
Or, to sort by favorite numbers, use:
Collections.sort(list, Student.FavComparator);
From the documentation for HashSet:
It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
So you cannot rely on HashSet to preserve any kind of order.
It looks to me like you just need to preserve the order of insertion, in which case you're better off not using a Set and rather a List, e.g.,
List<String> students = new ArrayList<>();

How do i sort an array of strings by the second char of each string?

I wrote a program that asks users to input names into an array and then the names are sorted in alphabetical order...The program works good but I was wondering if I could sort each of the names entered by the 2nd, 3rd, or 4th character in each string? For example, if the user entered Bob, Dan, and Kris the program should sort them as Dan, Bob, Kris. This is my program that sorts my array of strings by the first letter of the string:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SortingAnArrayOfStrings {
public static void main(String[] args) {
{
//Ask the user for names to add to the array
List<String> list=new ArrayList<String>();
Scanner in=new Scanner(System.in);
do {
System.out.println(" The names on the list are "+list);
System.out.println("Would you like to add another name to the list? (y/n)");
if (in.next().startsWith("y")) {
System.out.println("Enter:");
list.add(in.next());
}else{break;
}
} while (true);
//display the names that have been added to the array
System.out.println("The names on the list are "+list);
//sort the array of names in alphabetical order
String[] Arr=list.toArray(new String[list.size()]);
String[] stringArray=new String[Arr.length];
for(int i=0;i<Arr.length;i++)
{
for (int j = i+1; j < Arr.length; j++) {
if (Arr[i].trim().compareTo(Arr[j].trim())>0) {
String temp=Arr[j];
Arr[j]=Arr[i];
Arr[i]=temp;
}
}
stringArray[i]=Arr[i];
}
//display the sorted list of names
System.out.println("This is the list of names after sorting them in alphabetical order : ");
for(String ss:stringArray){
System.out.print(ss + " ");
}
}
}
}
You could try something like bellow using a custom java.util.Comparator:
String[] names = {"Dan", "Bob", "Kris"};
java.util.Collections.sort(java.util.Arrays.asList(names), new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.charAt(1) - s2.charAt(1);//comparision
}
});
for (String name : names) System.out.println(name);
output:
Dan
Bob
Kris
You could try this, just add a custom comparator by using Lambda expressions if you are using java version 1.8 or above :
list.add("Bob");
list.add("Dan");
list.add("Kris");
Collections.sort(list, (s1, s2) -> {
String sb1 = s1.substring(1);
String sb2 = s2.substring(1);
return sb1.compareTo(sb2);
});
System.out.println("list = " + list);
The Result:
list = [Dan, Bob, Kris]
I haven't tested this one but you could try this one. Replace the condition part of your code by this one.
Though, there may be some performance issue.
if (Arr[i].trim().compareTo(Arr[j].trim())>0) {
Replace with:
if (Arr[i].trim().charAt(nthChar) > Arr[j].trim().charAt(nthChar)) {
The nthChar is the character placement to compare.
Here is sample tested code. You need to use comparator so as to implement the order.
Here value of order can be anything based on your requirement. You can replace your current code with this because it is fine for normal sorting as well (based on index 0). It might require some tweaks based on your need.
String str[] = {"abc","bca","avc","ert"};
final int ORDER = 1;
Arrays.sort(str, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o1.toLowerCase().charAt(ORDER) - o2.toLowerCase().charAt(ORDER) ;
}
});
Add different implementations of java.util.Comparator based on the requirement and use
public static <T> void sort(List<T> list,
Comparator<? super T> c) in collections class to sort the list.
You want to use a custom comparator.

sort values in linked list

I have values in linked list as
TY12354d,sfasdf,asfasf,2.35123412E8
TY12354dsaf,asdffasd,asfasfafsd,12344.0
Pranish,pranishfilan,viper,1234
zxs,asdf,asfd,1234
uv,vr,va,1234
www,dsf,ASDF,123
dsfgsdf,sd,sd,235
The values are seperated by commas which contains certain data. The first ones i.e TY12354d, TY12345saf, Pranish etc are the id, second i.e sfasdf, asdffasd, pranishfilan, etc are name.The values are viewed in jtextfield. I want to enable user to sort the datas according to the id when he clicks on "sort by id" button, name when he clicks on "sort by name" button and so on.
Try this one to sort by id.
LinkedList<String> list = new LinkedList<String>();
list.add("TY12354d,sfasdf,asfasf,2.35123412E8");
list.add("TY12354dsaf,asdffasd,asfasfafsd,12344.0");
list.add("Pranish,pranishfilan,viper,1234");
list.add("zxs,asdf,asfd,1234");
list.add("uv,vr,va,1234");
list.add("www,dsf,ASDF,123");
list.add("dsfgsdf,sd,sd,235");
Collections.sort(list, new Comparator<String>() {
public int compare(String a, String b) {
System.out.println(a+" --> "+b);
return a.substring(0, a.indexOf(',')).compareTo(b.substring(0, b.indexOf(',')));
}
});
Use same concept for name also.
output:
Pranish,pranishfilan,viper,1234
TY12354d,sfasdf,asfasf,2.35123412E8
TY12354dsaf,asdffasd,asfasfafsd,12344.0
dsfgsdf,sd,sd,235
uv,vr,va,1234
www,dsf,ASDF,123
zxs,asdf,asfd,1234
--EDIT--
as per OP last comment to compare on Car object
class Car {
String id;
String name;
public Car(String id, String name) {
this.id = id;
this.name = name;
}
// getter & setter
}
LinkedList<Car> list = new LinkedList<Car>();
list.add(new Car("TY12354d", "sfasdf"));
list.add(new Car("TY12354dsaf", "asdffasd"));
list.add(new Car("Pranish", "pranishfilan"));
list.add(new Car("zxs", "asdf"));
list.add(new Car("uv", "vr"));
list.add(new Car("www", "dsf"));
list.add(new Car("dsfgsdf", "sd"));
Collections.sort(list, new Comparator<Car>() {
public int compare(Car c1, Car c2) {
return c1.id.compareTo(c2.id);
}
});
You'll have to write your own comparator, or rewrite the structure. With a comparator you can simply use Collections.sort to sort the list.
There are many threads on implementing comparators here on stackoverflow, like this one. It's actually fairly simple.
It's not very efficient to sort a linked list, so if you don't use Collections.sort, which uses an intermediate array to sort, I'd suggest that you change your datastructure to e.g. an array or ArrayList. Or, even better: create a Class to represent your data and define comparators for that class.
Here's an example of a Comparator:
import java.util.*;
class Test {
static class IDComparator implements Comparator<String> {
#Override
public int compare(String a, String b) {
return a.split(",")[0].compareToIgnoreCase(b.split(",")[0]);
}
}
public static void main(String[] args) {
LinkedList<String> ll = new LinkedList<String>();
ll.add("TY12354d,sfasdf,asfasf,2.35123412E8");
ll.add("TY12354dsaf,asdffasd,asfasfafsd,12344.0");
ll.add("Pranish,pranishfilan,viper,1234");
System.out.println("Before sorting on ID:\n");
for (String s : ll) {
System.out.println(s);
}
Collections.sort(ll,new IDComparator());
System.out.println("\nAfter sorting on ID:\n");
for (String s : ll) {
System.out.println(s);
}
}
}
Output:
Before sorting on ID:
TY12354d,sfasdf,asfasf,2.35123412E8
TY12354dsaf,asdffasd,asfasfafsd,12344.0
Pranish,pranishfilan,viper,1234
After sorting on ID:
Pranish,pranishfilan,viper,1234
TY12354d,sfasdf,asfasf,2.35123412E8
TY12354dsaf,asdffasd,asfasfafsd,12344.0
This is not the prettiest code I've written. I especially don't like the comparator itself, with a hard coded index. However, it'll give you an idea of how to proceed with custom comparators.

creating a map with duplicate keys

Consider the following question on storing values with duplicate keys:
Suppose there is a class Employee with name, sal and dob as attributes. I want to store the objects of Employee in a Map and the key would be the Employee name. The name can be duplicate.
Also after adding 10 objects in the Map. I want to retrieve the 8th object that was entered.
This is one solution to add objects with duplicate keys but for the 2nd part of the question, this would not work since on displaying the map, all values with the same key will be displayed together.
How would we maintain the order in which the objects were added in this situation? Can we modify equals and hashcode methods to somehow add the elements and then later retrieve them in the order in which they were inserted?
I think a LinkedHashMultimap (from Guava) should work for this. You wouldn't be able to get the 8th entry by index directly, but you could use something like Iterables.get(Iterable iterable, int position) to get it.
Why not just have two containers? One for mapping name to employee (like the one in the stackoverflow question you mentioned), another for mapping number to employee. You can make an "outer" container aggregating multimap and arraylist.
What you intend to do can be easily implemented using an ArrayList. This is the data structure that you should use.
The requirements are somehow contradictory. At one side several values should be possible for one key, at the other side only one value should be returned for a key. Additionaly, retrievals for a sequence should be possible. I see the nearest approximation in designing a dedicated data structure containing a hash map for fast access based on the name, and a list keeping the order of insertions. The access would be based on the overall sequence number or on the name plus index for the name. The implementation would be according the following lines:
public class Employee {
public String name; public int sal;
public Employee() {name = ""; sal = 0;}
public Employee(String name, int sal) {
this.name = name; this.sal = sal;
}
#Override public String toString() {return "(" + name + "," + sal + ")";}
}
public class Team {
private Map<String, ArrayList<Employee>> employees =
new HashMap<String, ArrayList<Employee>>();
private ArrayList<Employee> order = new ArrayList<Employee>();
public void addEmployee(Employee e) {
ArrayList<Employee> list = employees.get(e.name);
if (list == null) {
list = new ArrayList<Employee>();
employees.put(e.name, list);
}
list.add(e);
order.add(e);
}
public int getNumEmployees() {return order.size();}
public Employee getEmployee(int n) {return order.get(n - 1);}
public int getNumEmployees(String name) {
ArrayList<Employee> list = employees.get(name);
return list == null ? 0 : list.size();
}
public Employee getEmployee(String name, int n) {
ArrayList<Employee> list = employees.get(name);
return list == null ? null : list.get(n - 1);
}
}
// Test:
Team team = new Team();
team.addEmployee(new Employee("Bob", 11));
team.addEmployee(new Employee("Bob", 12));
team.addEmployee(new Employee("Eve", 13));
team.addEmployee(new Employee("Eve", 14));
System.out.println("Num all: " + team.getNumEmployees());
System.out.println("3rd: " + team.getEmployee(3));
System.out.println("Num Bobs: " + team.getNumEmployees("Bob"));
System.out.println("2nd Bob: " + team.getEmployee("Bob", 2));

How can I sort a List alphabetically?

I have a List<String> object that contains country names. How can I sort this list alphabetically?
Assuming that those are Strings, use the convenient static method sort:
Collections.sort(listOfCountryNames)
Solution with Collections.sort
If you are forced to use that List, or if your program has a structure like
Create List
Add some country names
sort them once
never change that list again
then Thilos answer will be the best way to do it. If you combine it with the advice from Tom Hawtin - tackline, you get:
java.util.Collections.sort(listOfCountryNames, Collator.getInstance());
Solution with a TreeSet
If you are free to decide, and if your application might get more complex, then you might change your code to use a TreeSet instead. This kind of collection sorts your entries just when they are inserted. No need to call sort().
Collection<String> countryNames =
new TreeSet<String>(Collator.getInstance());
countryNames.add("UK");
countryNames.add("Germany");
countryNames.add("Australia");
// Tada... sorted.
Side note on why I prefer the TreeSet
This has some subtle, but important advantages:
It's simply shorter. Only one line shorter, though.
Never worry about is this list really sorted right now becaude a TreeSet is always sorted, no matter what you do.
You cannot have duplicate entries. Depending on your situation this may be a pro or a con. If you need duplicates, stick to your List.
An experienced programmer looks at TreeSet<String> countyNames and instantly knows: this is a sorted collection of Strings without duplicates, and I can be sure that this is true at every moment. So much information in a short declaration.
Real performance win in some cases. If you use a List, and insert values very often, and the list may be read between those insertions, then you have to sort the list after every insertion. The set does the same, but does it much faster.
Using the right collection for the right task is a key to write short and bug free code. It's not as demonstrative in this case, because you just save one line. But I've stopped counting how often I see someone using a List when they want to ensure there are no duplictes, and then build that functionality themselves. Or even worse, using two Lists when you really need a Map.
Don't get me wrong: Using Collections.sort is not an error or a flaw. But there are many cases when the TreeSet is much cleaner.
You can create a new sorted copy using Java 8 Stream or Guava:
// Java 8 version
List<String> sortedNames = names.stream().sorted().collect(Collectors.toList());
// Guava version
List<String> sortedNames = Ordering.natural().sortedCopy(names);
Another option is to sort in-place via Collections API:
Collections.sort(names);
Better late than never! Here is how we can do it(for learning purpose only)-
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class SoftDrink {
String name;
String color;
int volume;
SoftDrink (String name, String color, int volume) {
this.name = name;
this.color = color;
this.volume = volume;
}
}
public class ListItemComparision {
public static void main (String...arg) {
List<SoftDrink> softDrinkList = new ArrayList<SoftDrink>() ;
softDrinkList .add(new SoftDrink("Faygo", "ColorOne", 4));
softDrinkList .add(new SoftDrink("Fanta", "ColorTwo", 3));
softDrinkList .add(new SoftDrink("Frooti", "ColorThree", 2));
softDrinkList .add(new SoftDrink("Freshie", "ColorFour", 1));
Collections.sort(softDrinkList, new Comparator() {
#Override
public int compare(Object softDrinkOne, Object softDrinkTwo) {
//use instanceof to verify the references are indeed of the type in question
return ((SoftDrink)softDrinkOne).name
.compareTo(((SoftDrink)softDrinkTwo).name);
}
});
for (SoftDrink sd : softDrinkList) {
System.out.println(sd.name + " - " + sd.color + " - " + sd.volume);
}
Collections.sort(softDrinkList, new Comparator() {
#Override
public int compare(Object softDrinkOne, Object softDrinkTwo) {
//comparision for primitive int uses compareTo of the wrapper Integer
return(new Integer(((SoftDrink)softDrinkOne).volume))
.compareTo(((SoftDrink)softDrinkTwo).volume);
}
});
for (SoftDrink sd : softDrinkList) {
System.out.println(sd.volume + " - " + sd.color + " - " + sd.name);
}
}
}
In one line, using Java 8:
list.sort(Comparator.naturalOrder());
Unless you are sorting strings in an accent-free English only, you probably want to use a Collator. It will correctly sort diacritical marks, can ignore case and other language-specific stuff:
Collections.sort(countries, Collator.getInstance(new Locale(languageCode)));
You can set the collator strength, see the javadoc.
Here is an example for Slovak where Š should go after S, but in UTF Š is somewhere after Z:
List<String> countries = Arrays.asList("Slovensko", "Švédsko", "Turecko");
Collections.sort(countries);
System.out.println(countries); // outputs [Slovensko, Turecko, Švédsko]
Collections.sort(countries, Collator.getInstance(new Locale("sk")));
System.out.println(countries); // outputs [Slovensko, Švédsko, Turecko]
Use the two argument for of Collections.sort. You will want a suitable Comparator that treats case appropriate (i.e. does lexical, not UTF16 ordering), such as that obtainable through java.text.Collator.getInstance.
Here is what you are looking for
listOfCountryNames.sort(String::compareToIgnoreCase)
more simply you can use method reference.
list.sort(String::compareTo);
By using Collections.sort(), we can sort a list.
public class EmployeeList {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> empNames= new ArrayList<String>();
empNames.add("sudheer");
empNames.add("kumar");
empNames.add("surendra");
empNames.add("kb");
if(!empNames.isEmpty()){
for(String emp:empNames){
System.out.println(emp);
}
Collections.sort(empNames);
System.out.println(empNames);
}
}
}
output:
sudheer
kumar
surendra
kb
[kb, kumar, sudheer, surendra]
You can use the following line
Collections.sort(listOfCountryNames, String.CASE_INSENSITIVE_ORDER)
It is similar to the suggestion of Thilo, but will not make a difference between upper and lowercase characters.
descending alphabet:
List<String> list;
...
Collections.sort(list);
Collections.reverse(list);
Java 8 ,
countries.sort((country1, country2) -> country1.compareTo(country2));
If String's compareTo is not suitable for your need, you can provide any other comparator.
Same in JAVA 8 :-
//Assecnding order
listOfCountryNames.stream().sorted().forEach((x) -> System.out.println(x));
//Decending order
listOfCountryNames.stream().sorted((o1, o2) -> o2.compareTo(o1)).forEach((x) -> System.out.println(x));
//Here is sorted List alphabetically with syncronized
package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
*
* #author manoj.kumar
*/
public class SynchronizedArrayList {
static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
#SuppressWarnings("unchecked")
public static void main(String[] args) {
List<Employee> synchronizedList = Collections.synchronizedList(new ArrayList<Employee>());
synchronizedList.add(new Employee("Aditya"));
synchronizedList.add(new Employee("Siddharth"));
synchronizedList.add(new Employee("Manoj"));
Collections.sort(synchronizedList, new Comparator() {
public int compare(Object synchronizedListOne, Object synchronizedListTwo) {
//use instanceof to verify the references are indeed of the type in question
return ((Employee)synchronizedListOne).name
.compareTo(((Employee)synchronizedListTwo).name);
}
});
/*for( Employee sd : synchronizedList) {
log.info("Sorted Synchronized Array List..."+sd.name);
}*/
// when iterating over a synchronized list, we need to synchronize access to the synchronized list
synchronized (synchronizedList) {
Iterator<Employee> iterator = synchronizedList.iterator();
while (iterator.hasNext()) {
log.info("Sorted Synchronized Array List Items: " + iterator.next().name);
}
}
}
}
class Employee {
String name;
Employee (String name) {
this.name = name;
}
}

Categories

Resources