How java Comparator is used ?
Here is a compare method of a Comparator
class AgeComparator implements Comparator{
public int compare(Object emp1, Object emp2){
* parameter are of type Object, so we have to downcast it
* to Employee objects
int emp1Age = ((Employee)emp1).getAge();
int emp2Age = ((Employee)emp2).getAge();
if(emp1Age > emp2Age)
return 1;
else if(emp1Age < emp2Age)
return -1;
else
return 0;
Question: How does these return makes a list in ascending / descending order ?
We use the above comparator this way.
//Employee array which will hold employees
Employee employee[] = new Employee[2];
//set different attributes of the individual employee.
employee[0] = new Employee();
employee[0].setAge(40);
employee[0].setName("Joe");
employee[1] = new Employee();
employee[1].setAge(20);
employee[1].setName("Mark");
//Sorting array on the basis of employee age by passing AgeComparator
Arrays.sort(employee, new AgeComparator());
user575089 wrote:
If so, I dont get the point why a FLAG return > is mapped with a ascending order ? whats the analogy here ?There's no "analogy." It's just convention. The rules say, "Our sort routine will ask you which of two objects is "less". If you return a negative number, we will take that to mean that the first object is "less than" the second," and so on.
Imagine someone gives you a deck of cards that's been shuffled and tells you to put it back in order. What would that order look like?
It might be:
A-spades
2-spades
3-spades
K-spades
A-clubs
and so on. That is, you might sort first by suit, then by rank, with spades being "less than" clubs, and so on.
Or it might be:
A-spades
A-clubs
A-hearts
A-diamonds
2-spades
with all the aces first, and the cards of the same rank being ordered by suit according to some rule.
Now, stop and think about the actual process of sorting the cards. There are several different approaches, but many of them involve the step: "Compare card X with card Y, and if they're in the wrong order, switch them." You understand that, right?
That is, if you're physically sorting cards, you will look at two cards, determine which one should come first, because it's "less than" the other card by whatever rules you're using, and then, if those cards are in the wrong order, you switch them. Do you understand this?
Now, if you understand that, do you understand that you can apply that step no matter what rules you have for determining which card is "less than" the other. In the first sample order I gave above, you might have the Ace of Diamonds in your left hand, and the King of Spades in your right. Since all Spades come first, you would switch them. But in the second example ordering, the rules say that all Aces come before anything else, so you would not switch them.
Your algorithm is: "Pick two cards, and if they're in the wrong order, switch them." That is, "if the one in the lower position is 'greater than' the other one, then switch them.".
That's what Arrays.sort() and Collections.sort() and SortedSet and SortedMap do. All that your Comparable.compareTo() or Comparator.compare() method does is tell the sort() methods which object is "less".
For example:
Card c0 = cardList.get(0);
Card c1 = cardList.get(1);
// if the card at position 0 is "greater than" the card at position 1...
if (c0.compareTo(c1)) > 0) {
// ... then switch c0 with c1
}Of course, the indices aren't hardcoded, and the choice of which pairs to compare is done intelligently, so that we will, on average, not make too many unnecessary comparisons, but this is the basic idea.
Similar Messages
-
How to compare dates using javascript?
Hi,
I have to compare dates using javascript. The dates are in format "mm/dd/yy" for eg "10/09/06".
I have written a script to compare the dates but the problem I 'm facing is with the year.
For example if I compare "10/09/06" with "10/04/98", then "10/04/98" is coming out to be greater than "10/09/06" because it is considering year "98" to be greater than "06".
Please advice/suggest.
Thanks in advance...Dude, you're here in a Java forum, not in a Javascript forum. Those are two entirely different languages.
The answer in Java is to use java.text.SimpleDateFormat to convert String to Date and use java.util.Date and/or java.util.Calendar to compare dates. -
How to compare MoM using SSAS in SSRS
Hello,
I have a cube which I want to use in SSRS to compare MoM. A user will pick up a date range using parameters and then I want to compare it with previous month.
Example:
Start Date : Jan 1 2015
End Date : Jan 31 2015
compare again Dec 1 2014 and Dec 31 2014
Report will look like like:
Sales
Jan 1 - Jan 31 2015 Dec 1 - Dec 31 2014 Variance % Variance
Product A 100 200
-100
Product B 50 40
10
Wondering how this can be achieved SSAS in SSRS.
Thanks,
P
mark it as answer if it answered your question :)Hello,
Thanks for the reply. I is surely helpful but here is the next challenge I have in this:
Just to give a run down, let's say user want to run a data for following date and want multiple comparison based on the date:
For example date entered by user is Jan 14, 2015 and he want to see the data
Jan 01 - Jan 14th for the MTD For Jan 2015
Dec 01 - Dec 14th for previous month
Oct 16 2014 to Jan 14 2015 (previous 90 days from Jan 14 2015)
Sep 15 2014 to Dec 14 2014 (previous 90 days from last date of previous month which is Dec 14th in this case)
Just wondering if this kind of date range can be calculated on fly to get the data.
Thanks,
P
mark it as answer if it answered your question :) -
How to compare MoM using MDX Query
Hello,
I have a cube which I want to use to compare MoM.
Example:
Start Date : Jan 1 2015
End Date : Jan 31 2015
compare again Dec 1 2014 and Dec 31 2014
Report will look like like:
Sales
Jan 1 - Jan 31 2015 Dec 1 - Dec 31 2014 Variance % Variance
Product A 100 200
-100
Product B 50 40
10
Wondering how this can be achieved SSAS.
Thanks,
P
mark it as answer if it answered your question :)Hello,
Thanks for the reply. I is surely helpful but here is the next challenge I have in this:
Just to give a run down, let's say user want to run a data for following date and want multiple comparison based on the date:
For example date entered by user is Jan 14, 2015 and he want to see the data
Jan 01 - Jan 14th for the MTD For Jan 2015
Dec 01 - Dec 14th for previous month
Oct 16 2014 to Jan 14 2015 (previous 90 days from Jan 14 2015)
Sep 15 2014 to Dec 14 2014 (previous 90 days from last date of previous month which is Dec 14th in this case)
Just wondering if this kind of date range can be calculated on fly to get the data.
Thanks,
P
mark it as answer if it answered your question :) -
Java Comparator - Sorting - using predefined order
I want to sort the items in my list with a predefined order....Is it possible? I can sort my List using a natural sort as in the below example. But that is not am looking for.....Am looking for sorting my list using an already defined order which i can hold using another list. IS IT POSSIBLE USING Comparator
package com.nationwide.ag.integration.adapter.party;
import java.util.*;
public class TestUsingMe {
static class AppComparator implements
Comparator {
public int compare(Object o1, Object o2) {
int cc = ((Integer)o1).compareTo(o2);
return (cc < 0 ? 1 : cc > 0 ? -1 : 0);
static Comparator appcomparator =
new AppComparator();
static void sort(List list1) {
Collections.sort(list1, appcomparator);
public static void main(String[] args) {
List list1 = new ArrayList();
list1.add(new Integer(90));
list1.add(new Integer(43));
list1.add(new Integer(21));
sort(list1);
System.out.println(list1);
Please reply................Tried as per your advice, as below. But, it didn't work out. (Hope I have done the changes correctly). Please find the changed code below:
import java.util.*;
import com.dto.search.PersonDTO;
public class TestUsingMe {
public static void main(String[] args) {
PersonDTO pDTO0 = new PersonDTO();
pDTO0.setCifId("Named Non-Owner");
PersonDTO pDTO1 = new PersonDTO();
pDTO1.setCifId("Restored");
PersonDTO pDTO2 = new PersonDTO();
pDTO2.setCifId("Antique/Classic");
List list1 = new ArrayList();
list1.add(pDTO0);
list1.add(pDTO1);
list1.add(pDTO2);
List list2 = new ArrayList();
list2.add("Private Passenger");
list2.add("Restored");
list2.add("Antique/Classic");
list2.add("Named Non-Owner");
list2.add("Trailer");
AppComparator appcomparator = new AppComparator(list2);
Collections.sort(list1, appcomparator);
static class AppComparator implements Comparator {
private List list;
public AppComparator(List list) {
this.list = list;
public int compare(Object o1, Object o2) {
return list.indexOf("cifId") - list.indexOf("cifId");
Please respond................... -
How to compare two files using MD5?
Hi,all:
How to compare two files to know if they're the same without any difference?I want to use MD5, but I just konw how get a message digest of a string. How to get a message digest of a file? Or there is other method to compare two files?
Thanks advance!This is starting to sound rather a lot like a homework problem.
An MD5 message digest is simply a 16 byte array. To compare two message digests...
byte[] md5incoming = ...
byte[] md5comparison = ...
if( md5incoming.equals(md5comparison) ) {
System.out.println("MD5 Checksums match");
}To find out how to generate an MD5 checksum, please look up MessageDigest in the API documentation, and do a google search for "MD5 java"
In a networked scenario, there are two issues - firstly the performance in sending copies of files all over the place (imagine if it's a 10Gb file to be compared over a 14.4K modem link, this would take a while). Secondly, the network link itself might insert an error in the file and you'd get a false miss.
By only sending MD5 digests over the link, you simultaneously reduce the error (shorter files are less likely to be corrupted) and reduce the transmission time (16 bytes takes practically no time to transmit over damp string, let alone any sort of sensible device).
D. -
Java Gurus: How does Java compare to 4GLs?
I've been using Java for a year now. I love Java. As a 3GL, how does Java compare to a 4GL?
(I can't say I know a whole lot about fourth generation languages. The only 4GL that I'm a little familiar with is Clarion.)
What are your thoughts?What is 3GLs and 4GLs? You mean Programming Language and Scripting Language?
-
Than how can i get java class by using it's class file?
Hi
After compilation of a java program, it creates a class file.
After getting class file suppose class file has been deleted.
Than how can i get java class by using it's class file?
Thanks in advance.get a decompiler and run your class file through it--I'll assume you want the source code back and that you are not trying to recover a missing class file by attempting to use the class file that is missing--if it's missing, then I've not a clue on how to get it back by using what is already missing.
BTW: many of your compilers have source control--if it does, just restore your missing file. -
How to compare two excel files in java ?
how do i compare two excel files in java.?
I have two excel files stored on my computer in d: drive.
Ex:
D:\\file a
D:\\file b
How to compare the contents of these two files and print " files are equal " or "files not equal "Javamastermahe wrote:
I mean i want to print on the console "files are equal " or any message like " both the files match "If this is your requirement, this program satisfies it...
import java.util.Random;
public class SuperExcelTester {
public static void main(String[] args) {
Random rnd = new Random();
String[] messages = {
"files are equal",
"files are not equal",
"unexpected error"
int index = rnd.nextInt(messages.length);
System.out.println(messages[index]);
} -
How to send attachments using java application and outlook
Hi ,
I created an application in java which is as
on the Conference Tab i can schedule a conference and with the send command on page it map all the scheduled data to outlook(with all conference details) and using outlook send option the mails are send to appropriate user.
but now i want to modify this application such as when i use the send command from my jsp page it should attach the file that is in .vcs or .ics format for auto updation of user calender.
can any one know how to send attachment using java application .Last time I checked, SMS was a service between carriers and doing SMS yourself was really tricky. Some services existed to let you do it but as I recall they wanted non-trivial money.
However, most phone carriers provide an email-to-SMS bridge of some kind.
So the easiest thing is just to send an email.
That's sending from a non-phone to a phone. There's a J2ME library to send/receive SMS from/to a phone.
However, this is from memory, and a little out of date, so I could be entirely wrong. Hope it helps anyway. -
How to start to work on MDM JAVA API by using webdynpro for java
Hi all
I have basic idea on MDM business package thru portal by using standard iViews.
now i am planning to work on MDM JAVA APIs by using Webdynpro for Java as UI.
1) can you please share the required documents on the same. how to start working on this by using MDM JAVA APIs in webdynpro for java
2) what are the JARs files are required and how to integrate those jar files into webdynpro for java application.
3) is there any SDN help on MDM JAVA API with webdynpro for java? . can you please send the link on the same.
4) can you please help by providing sample code on how to use JAVA APIs for retrieving,deleting,inserting and Updating the data in the database.
if anybody helps on the same then it is the great help to me.
points are always rewardable...
Regards
Suresh babuHi Suresh,
You can have the MDM JAVA API javadocs from the link
http://help.sap.com/javadocs/MDM/SP06P2/index.html
There you can see a package named com.sap.mdm.examples.The classes in it contains some examples using which you can start understanding the code.
You need to have MDM JAR files for it. And these JAR files to be used at build time can be added to the project thru :-
Right click on project-> properties->Java Build Path - > Add external JARs
At run time you can add them the reference in
Right click on project-> properties->web dynpro references->library reference.
Thanks
Namrata -
How to compare two files in java & uncommon text should print in text file.
Hi,
Can any one help me to write Core java program for this.
How to compare two files in java & uncommon text should print in other text file.
thanks
SamHi All,
i m comparing two HTML file.. thats why i am getting problem..
import java.io.BufferedReader;
import java.io.FileReader;
public class textmatch{
public static void main(String[] argv)
throws Exception{
BufferedReader fh =new BufferedReader(new FileReader("internal.html"),1024);
BufferedReader sh = new BufferedReader(new FileReader("external.html"),1024);
String s;
String y;
while ((s=fh.readLine())!=null)
if ( s.equals(y=sh.readLine()) ){
System.out.println(s + " " + y); //REMOVE THIS PRINTLN STATEMENT IF YOU JUST WANT TO SHOW THE SIMILARITIES
sh.close();
fh.close(); }
thanks
Sam -
How to compare two files in Java & uncommon text should print in Diff text
Hi All,
can any one help me to write a java program..
How to compare two files in Java & uncommon text should print in Diff text file..
Thanks
SamHi All,
i m comparing two HTML file.. thats why i am getting problem..
import java.io.BufferedReader;
import java.io.FileReader;
public class textmatch{
public static void main(String[] argv)
throws Exception{
BufferedReader fh =new BufferedReader(new FileReader("internal.html"),1024);
BufferedReader sh = new BufferedReader(new FileReader("external.html"),1024);
String s;
String y;
while ((s=fh.readLine())!=null)
if ( s.equals(y=sh.readLine()) ){
System.out.println(s + " " + y); //REMOVE THIS PRINTLN STATEMENT IF YOU JUST WANT TO SHOW THE SIMILARITIES
sh.close();
fh.close(); }
thanks
Sam -
How to resize image using java imageio
Hello ,
I want to know how to resize image using java imageio.
I dont want to use java awt because i am writing a web application.
help is very much needed
thank you.Just use an AffineTransform !
Its much easier -
How to convert oracle form fmb file to java swing file using Jdeveloper
how to convert oracle form fmb file to java swing file using Jdeveloper.Please explain with detailes steps if possible or please give a link where it is available
thanks
Message was edited by:
user591884There is no automatic way to do this in JDeveloper. I know there are some Oracle Partners offering forms to java conversion, I don't know how much of their tools are automated and done with JDeveloper. With JDeveloper+ADF you basically rewriting the Forms application from scratch (and using ADF is helpful during this process).
Maybe you are looking for
-
I have an iphone 5 synced to my mac and also connected a samsung s3 to kies(samsung alternative to itunes). For some reason i now have all my dads contacts as well as my own and vice versa. How can i stop this happening?
-
ERROR while uploading data from EXCEl to sap using ALSM_EXCEL FUNCION MODULE
Hi Experts, I am uploading excel data into sap suing function module ALSM_EXCEl_TO_INTERNAL_TABLE , used this funcion module in the program while running the program one blank excel sheet is opening and data is not uploading into internal table . eve
-
Hard drive problem with Pavillion DV9722EG notebook
I have the a.m. notebook with a single 250GB hard drive installed, and there is an empty slot for a second hard drive. I tried to install a second hard drive, but the hard drive is not recognised in any way in BIOS... the BIOS is the latest version f
-
Hi friends, Kindly let me know whate is web services, how to start work on that. My client requirement for couple of objects is: 1. Create a web service which can perform the following actions: a. Read the XML input file. b. Perform the action define
-
Change default Remote settings to open a different app than Front Row?
Hello! Forgive me if this is not the right board for this post, but I'm not sure where it should go exactly - this seemed best. I have a fairly new MacBook Pro running Leopard, a rather large video library on an external drive, and a 24" display atta