This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Match the most closest number Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Match the most closest number " Watch "Match the most closest number " New topic
Author

Match the most closest number

jay lai
Ranch Hand

Joined: Apr 04, 2002
Posts: 180
I have a list of number, types is Double. I have a method to pass in the Double as params. I want to compare the input params with each of the values in the collection, if it matches the most closest value then return that value from the collection.

Collections<Double> list = new ArrayList<Double>();
list.add(89000.00);
list.add(78900.00);
list.add(56999.12);

so the method is like this

private Double getTheMatch(Double param) {
pseudo code:
for (Double d : list) {
if (param Match list.getNumber) {
return list.getNumber;
}
}
}

so if passing 88908.00 --> value will return will be 89000.00 , the most match value from the list

What API java class should I use? Thanks
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

You can use a NavigableSet for this. Class TreeSet is an implementation of class NavigableSet. Example:

Note that the method ceiling returns the least element in the set greater than or equal to the given element (or null if there is no such element). There are other methods in the interface, such as floor, higher and lower. You'll have to read the documentation and decide which of these is appropriate for your application.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
jQuery in Action, 2nd edition
 
subject: Match the most closest number
 
Similar Threads
Bad practise? JavaBean where setX() actually should be addX()?
Calculating a Given Value From an Array of integer
Wild card ? extends Number in return of a method ?
where do we write EJB-QL in DD
Generics and a copy method