Lower_bound(), upper_bound() functions for sorted containers
I can't find lower_bound(), upper_bound() functions for sorted containers in the java library. It doesn't seem to be there in the apache commons either.
i'm referring here to the meaning as defined in STL (C++) as in:
http://www.cplusplus.com/reference/algorithm/lower_bound/
http://www.cplusplus.com/reference/algorithm/upper_bound/
These functions are extremely useful for range lookups. Why is this not readily available in the java libraries?
How I would write the Java code for the problem you stated on the blog:
import java.util.Arrays;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.Map.Entry;
public class TestNavigable {
public static void main(String[] args) {
NavigableMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
map.put(10, 100);
map.put(25, 212);
map.put(30, 212);
map.put(200, 400);
for (int check : new int[] { -1, 0, 5, 11, 26, 30, 100, 400 }) {
Entry<Integer, Integer> upper = map.ceilingEntry(check);
if (upper != null) {
Integer lower = map.lowerKey(upper.getKey());
if(lower == null) {
System.out.println(check + " falls into range up to "
+ upper.getKey() + " and maps to " + upper.getValue());
else {
System.out.println(check + " falls into range <" + lower + ", "
+ upper.getKey() + "] and maps to " + upper.getValue());
else {
System.out.println(check + " is out of range!");
// if you want to use arrays for other reasons
// note: would require to keep keys/values in sync if not sorted
int[] keys = { 10, 25, 30, 200 };
int[] values = { 100, 212, 212, 400 };
for (int check : new int[] { -1, 0, 5, 11, 26, 30, 100, 400 }) {
int index = Arrays.binarySearch(keys, check);
if(index < 0) {
index = -(index + 1);
// good enough if no duplicate elements in keys
// see binarySearch javadoc
int lower = index - 1;
int upper = index;
if (upper < values.length) {
if(lower == -1) {
System.out.println(check + " falls into range up to "
+ keys[upper] + " and maps to " + values[upper]);
else {
System.out.println(check + " falls into range <" + keys[lower] + ", "
+ keys[upper] + "] and maps to " + values[upper]);
else {
System.out.println(check + " is out of range!");
}I'm too spoiled to write a binary search like you did ;-).
Similar Messages
-
Sorting a Collection with dynamic columns using a custom compare function for multiple columns
I need help and ideas on how to sort a ListCollectionView. My problem is complicated by 3 requirements-
1. The column values contain HTML tags that needs to be removed before sorting (use custom compareFunction to strip HTML)
2. The columns are dynamic, so dataField names are not known at compile time (need a single compareFunction for all columns)
3. The data is used in an AdvancedDataGrid so multi-column sorting is required
I have figured out how to solve any 2 of the 3 requirements. However, I am having difficulties supporting all 3 requirements.
Any help or ideas would be greatly appreciated. Thanks.After playing with this some more I think I've figured out a solution. This seems to work in initial testing. Also, there is not a need to capture the current sort column in the headerRelease event which many offered solutions suggested. Another benefit to this solution is that keyboard initiated sorting is handled also. Whereas the headerRelease event is only triggered by a mouse click on the column header and special handling is required if the user uses the keyboard to access the column header.
One point that I don't understand is how ascending/decending order is determined. Behavior seems to be different between a single SortField versus multiple SortFields. Notice how the compareResults are handled for the different situations. Anyone out there know why???
private function colSortCompareFunction(obj1:Object, obj2:Object, fields:Array = null):int{
var compareResults:int = 0;
var newObj1:Object = new Object();
var newObj2:Object = new Object();
// should not be a condition that is met
if (_dataProviderDetails.sort.fields == null) {
var s:Sort = new Sort();
var f:Function = s.compareFunction;
return f.call(null, obj1, obj2, fields); }
// when a single column is selected for sorting
else if (_dataProviderDetails.sort.fields.length == 1) {
var firstFld:SortField = _dataProviderDetails.sort.fields[0];
newObj1[firstFld.name] = stripHTML(obj1[firstFld.name]as String); newObj2[firstFld.name] = stripHTML(obj2[firstFld.name]
as String);
compareResults = ObjectUtil.compare(newObj1[firstFld.name], newObj2[firstFld.name]);
return compareResults; }
// when multiple columns are selected for sorting
else {
for each (var fld:SortField in _dataProviderDetails.sort.fields) {
newObj1[fld.name] = stripHTML(obj1[fld.name]
as String); newObj2[fld.name] = stripHTML(obj2[fld.name]
as String);
compareResults = ObjectUtil.compare(newObj1[fld.name], newObj2[fld.name]);
if (compareResults != 0) {
if (fld.descending) {
return compareResults * -1; }
else {
return compareResults; }
return compareResults; }
Does anyone see any problems with this solution?
NOTE: stripHTML(String) is a simple function using regular expression to remove HTML tags.
Thx -
Sort function for Iphone??
I was so glad today when I received the latest update containing the function to sort playlists only to find out it only applied to Ipad.
Why is it so hard to get this function for Iphone?
Has anybody heard of when the sorting function will be released for Iphone?I saw that! Amazing!
I can't believe it took so long. Kind of disrespecfulnto call it a "small change" in the change notes. If it was that small, why irritate a whole community by not applying it sooner?
Now you/they just have to work on it remembering the chosen sorting when leaving and reselecting a playlist. As of now sorting goes back to default if you leave a playlist. -
Implementing sort functionality for Z fields in inbox items
Hi all,
i have a requirement where i got to add a Z-field in the "Sort by" as well as "Then Sort by" dropdown in the inbox search. I have managed to add the item, nevertheless, i am unable to implement the sort functionality for the same.
Can someone help?
Is there anyways of making this simple?
Thanks in advance,
NishaHi Jason,
thank you very much with the note 1388298 our
Z-fields on the web-dynpro for "Item Basic Data" are visible now.
We have also Z-fields for "Account Assignment".
This fields are still not available.
Is it also possible to add these fields with component configuration?
I haven't found anything in the oss.
You will get 10 points because my original question has been answered.
Thanks in advance for your help!!
Kind Regards
Stefan -
Anchor link only for image in table header for sorting
Hi,
I need to implement sorting functionality for datatable.
for sorting header of the table column will have image along with header text.
for this i am using <h:commandLink> and <h:graphicImage>.
But i am getting behaviour as anchor link for both text and image.
deserved behavior for this is only ofr Image.
If any one implemented the same ..please help me
RegardsTry:
Sub ClearKeepWNext()
Dim Tbl As Table, i As Long
For Each Tbl In ActiveDocument.Tables
With Tbl
.Range.ParagraphFormat.KeepWithNext = False
For i = 1 To .Rows.Count
With .Rows(i)
If .HeadingFormat = True Then
.Range.ParagraphFormat.KeepWithNext = True
Else
Exit For
End If
End With
Next
End With
Next
End Sub
If the tables only have a single heading row, you could instead use:
Sub ClearKeepWNext()
Dim Tbl As Table
For Each Tbl In ActiveDocument.Tables
With Tbl
.Range.ParagraphFormat.KeepWithNext = False
With .Rows(1)
If .HeadingFormat = True Then
.AllowBreakAcrossPages = False
End If
End With
End With
Next
End Sub
Cheers
Paul Edstein
[MS MVP - Word] -
Aggregate functions for internal table.
Hi Gurus,
I'm just wondering whether we can use aggregate functions for internal table. I wanted to know the max value for a particular column in my internal table. How can I achieve this easily and quickly.
Thanks,
David.sort the table on which you want the maximum value and read it. Please find below example code.
TYPES : BEGIN OF ty_mvke,
matnr TYPE mvke-matnr,
vkorg TYPE mvke-vkorg,
vtweg TYPE mvke-vtweg,
AUMNG type mvke-AUMNG,
END OF ty_mvke.
DATA : wa_mvke TYPE ty_mvke,
it_mvke TYPE STANDARD TABLE OF ty_mvke.
data : temp_AUMNG type AUMNG.
START-OF-SELECTION.
SELECT matnr vkorg vtweg AUMNG FROM mvke INTO
table it_mvke.
sort it_mvke by AUMNG.
read TABLE it_mvke into wa_mvke INDEX 1.
if sy-subrc = 0.
move wa_mvke-AUMNG to temp_AUMNG.
write : temp_AUMNG.
endif.
Thanks,
Sreekala. -
Designerd does not generate Order BY code for Sort Order on a lookup tabel column.
I am setting the Sort Order on a column which is based on a lookup table.
When generate the the module, designer does not generate the code for the Sort Order that I set on the lookup table column.
Is there a work around for this problem or is there some thing else that needs to be done in designer to make it generate the order by clause?
I will very much appreciate help.
Regards
Prasad.A bound lookup item, will be generated as a NON-database item in Forms. Designer generates an ORDER BY CLAUSE (a Forms Block property) for the ordering. But a NON-database item cannot be included in the ORDER BY CLAUSE.
I used a stored function for ordering the lookup item.
Best regards
Harm van Zoest -
Custom tool bar for sorting and summing in alv grid
what is the function module to use the tool bar in the alv output screen which has - summing , sorting and other button above the alv grid control.
It is part of the class CL_GUI_ALV_GRID. Have a look at this class, especially the methods within this class, and search for 'SORT' or 'TOTAL' using the button with 'Binoculars' icon.
-
Hi Guys,
I am doing scenario File to Idoc, i have to sort date in acending order, the date format will be in either 22.10.2007 or 22/10/2007 . can any one send UDF for this.
Regards,
venu gopalHi Venu
You can execute this without UDF. Use " Transform" function in the Date functions.
When you are using the UDF....you keep the strucure as "yyyMMddhhmmss" for that clickon Trnasform function and there you can see ShowAdvancedProperties...there u can find the format of the source which you are expecting and also change the strucutre of you target expected format.
You please try this and check the mapping it will get execute.
Use Standard Date Function DATATRANS. It have the property for format and input is the source date field. It will convert the date format to required specified format which you menstion in the DARTATRANS function
for UDF
Re: UDF for this mapping rule
Re: Problem in UDF please Help?
Thanks! -
Creating multiple partner function for a sale order @ header level
Hi All,
I have a requirement where in i have to create more than one partner funtion for a sale order @ header level. But the system did not allow this sort of scenario and i got the error,
Partner function ZZ can only occur 1 times in procedure TA (Sales Document Header)
the function module that was giving this error was SD_PCHECK_PARVW_COUNT_OK
here the function module checks if a partner function already exists if so it throws that error. This also updates the VBPA table where partner function is one of the key fields.
Our issue is that we have to allow the system to enable posting 2 or more partner function for the same sale order. It was also verified that the unique key was unchecked during configuration.
is there any other way of over coming this issue as we are updating the standard table. Is it possible??
Thanks a lot in advance for your reply....I believe this is a configuration setting, based upon the details of your post. Typically, a sales order can have multiple partner functions, but usually the partner type is not duplicated at a single level (header or one item). For example, it would not be logical to have multiple ship-to partners at the header level...these would be unique at the item level, if required.
Speak to your SD functional specialist about the configuration controls for partners, if you must have more than one partner with parvw = ZZ, for the entire order (header level).
Edited by: DaveL on Aug 23, 2011 3:00 PM -
BDC Recording for Sorting a coloum
Hi All,
I have to do BDC Recording for a transaction.During recording i have to select a coloum and sort it ascending and then do further processing.
BDC recording happens for sorting but not for selecting coloum.
and hence it gives error when we process the recording that "Select a coloum".
can u plz tell me how to add seelcting coloum in BDC recorording.
ThanksHi,
You should try to incorporate your functionality using FIND or POSITION button instead of going for sort option.
Find or position button work very good in this scenerio. With find button you can find the desired entry easily.
Hope this will solve your problem.
Regards,
Brajvir -
Is there a way to set up an automatic paste function for frequently used phrases
Is there a way to set up an automatic paste function for frequently used phrases.
My husband has an unusually long email address which he cannot change - he is not good at typing. I would like to help him by creating a sort of shortcut or auto paste function on his IMac to save him time and frustration. Any suggestions?
ThanksAre you really using an earlier OS than Mac OS 8.6? That would be either 8.1, or 8.5 if I recall correctly.
Apple's classic forum, see:
https://discussions.apple.com/community/mac_os/classic_mac_os?view=discussions#/ ?tagSet=1037
You need to look for:
-- remap or rename keyboard keys
-- keyboard macros
At this site look for
http://trace.wisc.edu/world/computer_access/mac/macshare.html#applwindows
EasyTyper 1.0.2
TypeIt4Me
resEdit maybe a possibility ... free
http://hintsforums.macworld.com/archive/index.php/t-32745.html
You could creae a file with common words & phrases in it & copy & past.
SmartKeys 3
http://trace.wisc.edu/world/computer_access/mac/macshare.html#applwindows
Robert -
BI IP --- Planning function for File Upload
Hai All,
In BI IP , When I am trying to load the data (text file) by using Planning function for File Upload. I am getting an error message When I am clicking on Update .
Error Message : Inconsistent input parameter (parameter: <unknown>, value <unknown>).
In Text file I am using Tab Separation for each value
Anyone help me out.
Thanks,
BhimaHi Bhima
Try one of these; it should work:
1. If you are on SP 14 you would need to upgrade to SP 15. It would work fine
2. If not, then -
a] apply note 1070655 - Termination msg CL_RSPLFR_CONTROLLER =>GET_READ_WRITE_PROVIDS
b] Apply Correction Instruction 566059 [i.e: in Object - CL_RSPLFR_CONTROLLER GET_READ_WRITE_PROVIDS,
delete the block: l_r_alvl = cl_rspls_alvl=>factory( i_aggrlevel = p_infoprov ).
and insert block - l_r_alvl = cl_rspls_alvl=>factory( i_aggrlevel = i_infoprov ).
Goodluck
Srikanth -
Is there any functionality for AVERAGE in ALV, like do_sum, subtot?
Hi Experts,
In my_alv report, am doing sub/totals for prices, by using do_sum, subtot functions.........fine. But, I need to do/display the AVERAGE value for Discount % column?
Is there any functionality for AVERAGE in ALV, like do_sum, subtot?
thanqhi
check these links out
http://www.sapfans.com/forums/viewtopic.php?t=20386
http://www.sapfans.com/forums/viewtopic.php?t=85191
http://www.sapfans.com/forums/viewtopic.php?t=88401
http://www.sapfans.com/forums/viewtopic.php?t=17335
regards
vijay
reward points if helpful -
Crash on search function for HTML Help file (.chm) when
connected to a Visual C++ application
I use the RH_ShowHelp API command to connect a HTML Help file
(.chm file generated by RoboHelp Word X 5) to my Visual C++
application. My application is able to call up this HTML help file
in context-sensitive mode and everything is working great in the
Contents and Index panels EXCEPT when I click on List Topics (after
I enter a KEYWORD for search) in the Search panel.
I got an error that said “Unhandled exception in
xxxx.exe.(HHCTRL.OCX):0xC00000FD: Stack overflow”
I am able to execute this .chm file by itself and the search
function works well in this case. I am using HHActiveX.dll that is
created on 2/23/04. Is this the correct version?? Any advice what
to do here??Hi agschin and welcome to the RH forums. The hhactivex.dll
file is not used by the search function so you can rule that our.
Have you tried recompiling and seeing if the problem still happens?
You can also start the Bug Hunter feature in RH - View > Output
View and then select the Bug Hunter button - and see if that throws
up any clues.
Maybe you are looking for
-
How can I make my Mac mini recognise again iomega external hard drive, if it has stopped to do so? many thanks.
-
Error when using Oracle Migration WorkBench (Sql Server 2k to Oracle 8i)
I'm trying to migrate a Sql Server 2k database to an Oracle 8i schema using OMWB. After using BCP to collect metadata information on the source database, I tried to capture the source data model and got a "Capture aborted" message on the progress scr
-
What is the best way to create a multilingual site using adobe Muse?
hello, inside Muse its ok with linking the menus to the different language sites, BUT if my site in german have 20 pages and i have to made the tablett and sphone version, will this be to heavy for Muse ? (of course the images will be optimised to th
-
Error in replacing the bytes.
Hi all, I like to implement "System.arraycopy" method of java in objective C. I have implemented as follows : +(BOOL)copyBuffer:(NSData *)srcdata_ :(int)srcIndex :(unsigned char*)dest :(int)destIndex :(int)destLength BOOL isCopied = YES; @try NSMutab
-
Hi.. The requirement is as follows : SAP drops a file into a folder and triggers a UNIX script using a File Port partner destination. Unix script will perform a secure copy to the Webmethods server. If a Unix script error occurs, an Rfc function wil