Want to sort HashMap based on Values with duplicate values
Hi. I have a requirement to sort the HashMap based on the values not on the keys. My HashMap contains the values which are duplicates. My program is some thing like this.
Map m = new HashMap();
m.put ("Gosling", new Integer(2000));
m.put ("Joy", new Integer(2000));
m.put ("Schwartz", new Integer(3000));
m.put ("Bracha", new Integer(4000));
m.put ("Gafter", new Integer(3000));
still i need to sort HashMap based on the values. How can i do it. I want the output some like this.
Gosling 2000
joy 2000 (may be interchanged)
Schwartz 3000
Gafter 3000 (Same as above)
Bracha 4000
Thanks.
I found syntactical problems with above mentioned code.
Here is edited working version:
* test sortMap
public void testSortMap () {
Map m = new HashMap();
m.put ("IGGHHG", new Integer(232353453));
m.put ("ASDF", new Integer(345555000));
m.put ("DSF", new Integer(345555000));
m.put ("XYZ", new Integer(45555555));
m.put ("AAA", new Integer(0));
ArrayList outputList = sortMap(m);
int count = 0;
count = outputList.size();
while(count > 0) {
Map.Entry entry = (Map.Entry) outputList.get(--count);
System.out.print("Key:" + entry.getKey());
System.out.println("\tValue:" + entry.getValue());
* This method will use Arrays.sort for sorting Map
* @param map
* @return outputList of Map.Entries
public ArrayList sortMap(Map map) {
ArrayList outputList = null;
int count = 0;
Set set = null;
Map.Entry[] entries = null;
// Logic:
// get a set from Map
// Build a Map.Entry[] from set
// Sort the list using Arrays.sort
// Add the sorted Map.Entries into arrayList and return
set = (Set) map.entrySet();
Iterator iterator = set.iterator();
entries = new Map.Entry[set.size()];
while(iterator.hasNext()) {
entries[count++] = (Map.Entry) iterator.next();
// Sort the entries with your own comparator for the values:
Arrays.sort(entries, new Comparator() {
public int compareTo(Object lhs, Object rhs) {
Map.Entry le = (Map.Entry)lhs;
Map.Entry re = (Map.Entry)rhs;
return ((Comparable)le.getValue()).compareTo((Comparable)re.getValue());
public int compare(Object lhs, Object rhs) {
Map.Entry le = (Map.Entry)lhs;
Map.Entry re = (Map.Entry)rhs;
return ((Comparable)le.getValue()).compareTo((Comparable)re.getValue());
outputList = new ArrayList();
for(int i = 0; i < entries.length; i++) {
outputList.add(entries);
return outputList;
}//End of sortMap
Similar Messages
-
Sorting HashMap based on values
I need to sort a hashmap based on the values, but also need to keep the keys available for retrieving the values.
Example:
key value
1 c
2 a
3 b
Desired Result
2 a
3 b
1 c
Thanks for your help.You can do this by getting all the Map.ENTRY values in a HashMap object then using a custom Comparator object to sort them by value.
like this:
HashMap hashMap = // your HashMap
Set entrySet = hashMap.entrySet;
/* Now add them into a list and use the Collections
* class to sort them.
ArrayList list = new ArrayList();
list.addAll(entrySet);
Collections.sort(list, yourSpecialComparator);Hope this helps. -
Hi All,
Query result gives ou put like in the following order
CITY NAME
CHENNI
DELHI
LONDON
RIO DEGENERO
How to get output in the following sort order
LONDON
CHENNAI
DELHI
RIO DEGENERO
i dont want to hardcode the column values ..it will be great if i get option to genrate dynamically.
Thanks!Hi,
user601042 wrote:
Hi All,
Query result gives ou put like in the following order
CITY NAME
CHENNI
DELHI
LONDON
RIO DEGENERO
How to get output in the following sort order
LONDON
CHENNAI
DELHI
RIO DEGENERO
i dont want to hardcode the column values ..it will be great if i get option to genrate dynamically.If the sort order isn't hard-coded, how do you get it?
If you call a function to get the sort order, then just call the function in the ORDER BY clause:
ORDER BY sort_key (city_name)If the sort order is in a table, join to that table, so you can use the appropriate column
FROM table_x x
JOIN cities c ON c.city_name = x.city_name
ORDER BY c.sort_key
user601042 wrote:... i want to display the following order in screen
3 LONDON
1 CHENNI
2 DELHI
4 RIO DEGENEROThe question is, how do you determine that order? I don't see anything obvious in the data itself.
If you were sorting by the id, either ascending or descending, then 1 wouldn't come between 3 and 2.
If you were sorting by alphabetic order, either ascending or descending, then 'CHENNI' wouldn't come between 'LONDON' and 'DELHI'.
If you were sorting by the length of the name, either ascending or descending, then 'DELHI' (5 characters) wouldn't come between 'CHENNI' (6 CHARACTERS) and 'RIO DEGENERO' (12 characters).
By what are you sorting? If you can explain it in English, then someone can help you code it in SQL.
Edited by: Frank Kulash on Oct 17, 2012 2:40 PM -
Sorting numbers based on value into arrays
Hi ...
I currently have a large list of numbers inside an array.. say from 0 to 400 000. They appear in order, but are unevenly spaced.
Now I'd like to sort these numbers into arrays.
I want to say: Put all numbers from 0 to 10 into newArray[0]. Put all numbers from 10 to 35 into newArray[1] ....
In the end I need a two - dimensional array with numbers. Is this possible in LabView ? Can it be done in acceptable speed ?
Thank you for your helpWhile I haven't figured out a way to do this efficiently, the attached
shows a method of doing it number by number. Perhaps the most
efficient may be to insert Matlab code and use a sort function, or
equivalent in c.
To use this to sort multiple numbers, put inside a for loop and build up an array. (also see attached).
Message Edited by Robert.Bedford on 09-19-2005 08:53 AM
Attachments:
single_number_sort.vi 18 KB
array_sort.vi 21 KB -
Want to sort the records based on non-base table item
I have a multi-record block and I am trying to sort the data based on nbt item
I have a table called X which has x_type,x_code fields.
The table on which the block is created is Y. the table Y has x_type and y_desc as its fields
form layout is like below .the x_type is key field on which I have to query the records
and x_code is a non-base item in the form.I want to sort the records by X_code.
x_code y_desc
A xyz
c par
B lmn
my pre-query has this code
select x_type from y
where
x_type := x_type;
post-query has this code
select x_code from x
where x_type = :x_type;
It works fine in Enter-Queryand execute query mode. but when I am sorting the records on
nbt item x_code by SET-BLOCK-PROPERTY it doesn't do any thingHi Tony ,
I have created a function and in Pre-Query & have add this
SET_BLOCK_PROPERTY('b1', ORDER_BY, 'fn_get_code(x_type)');
and the function created is as below
Function fn_get_code (p_x_type in varchar2) return varchar2 is
v_code varchar2(40);
begin
select x_code into v_code
from X, Y
where X.x_type = Y.x_type
and y.x_type = p_x_type
return v_code;
end;
when I run the form and execute query it comes up with the error message
FRM-40505 and when I pressed display error it shows
SQL Statement error:
SELECT ROWID,X_TYPE,X_CODE
FROM Y order by fn_get_code(x_type)
Error:
"ORA-00904: "FN_GET_code": invalid identifier"
Is it that I need to create a function on the database?. As I have created function
in program unit section -
Hi, Unfortunately my Laptop has died (which had my iTunes on it). I want to ensure my music on my iPhone 5 and my iPad Air are backed up. Also, I want to sort my music in the way I used to with iTunes. How can I do this with just these two devices, i.e. NO Computer? Can the iCloud help? Why can't I download iTunes (i.e. my library as I saw it on the computer) to these devices? Thanks to anyone who can help me here.
You can change the email address of one's appleID...
I'd recommend changing moms email to yours to get a good backup on the Mac
Then switch mom's back to hers
Then change your account to the same email you used.
I've done something similar when I needed to update my Apple account (one ID changing email addresses and phone) -
I have € 0.09 in my account and I can not buy anything with this value. I want to undo (give up) this value. What do I do?
Click here and request assistance.
(68968) -
Want 2 populate value in 2nd list item based on value selected in 1st list?
Want 2 populate value in 2nd list item based on value selected in 1st list?
Gaurav -
The 3rd list will not populate because nothing has been selected yet in list 2. The value in list 2 is null, so the loop to populate list (3) has nothing to load. Try the following below. This should seed your 2nd list so the 3rd list will populate.
You will have to declare first_record boolean and first_value to match DESCC.
first_record := true; -- NEW *****
Clear_List('BLOCK2.ITEM2');
FOR CurRec IN (SELECT UNIQUE DESCC DESCC FROM LUTT where LUTT.IDD = :BLOCK2.ITEM1)
LOOP
if first_record = true then -- NEW SECTION *****
first_value := CurRec.DESCC;
first_record := false;
end if;
Add_List_Element('BLOCK2.ITEM2',1,CurRec.DESCC,CurRec.DESCC);
END LOOP;
:block2.item2 := first_value; -- NEW *****
Clear_List('BLOCK2.ITEM3');
FOR CurRec2 IN (SELECT UNIQUE DESCC DESCC FROM LUTT where LUTT.DESCC = :BLOCK2.ITEM2)
LOOP
Add_List_Element('BLOCK2.ITEM3',2,CurRec2.DESCC,CurRec2.DESCC);
END LOOP;
My name is Ken, 1990 is when I started using Oracle Forms 3.0, character based in the Unix environments. And you are very welcome. -
How to sort HashMap by values?
?
You can create a TreeMap out of your HashMap using the values as the key. Just remember that the keys can not be duplicates.
Bosun -
I need your valuable suggestion on how to create the Value based shipment cost.
Our Process:
Create POS - Create Inbound delivery - Create Shipment - Create Shipment cost - Post Inbound Delivery.
So while posting the inbound delivery, the freight cost will post against the material. The invoice will be paid for the Vendor for the quantity purchased and freight charge will be paid for the freight Vendor(s).
We are adding the Vendor in the Shipment and adding the cost against the Vendor in the Shipment Cost.
Everything is working fine, but the shipment cost posting against the material was happening based on the delivery weight / quantity.
The reason for this asking the question is - we are receiving high value items and low value items with the same weight.
Question 1: Is it possible to have the shipment cost being split, calculated and posted against the material based on the PO Item received Value or PO Price
Quesion 2: Is it possible to post the shipment cost at a later date? Currently, the shipment cost posts when the inbound delivery is received (I know the material value will be posted when there is stock changes or price changes). But our issue is the invoice for the shipment cost will be received after a couple of days from the goods receipt. Right now we are entering couple of costs through assumption, then while postig the invoice, we adjust that value.
Note: I cannot enter the condition directly in the PO, as the same PO item will be partially received by multiple inbound deliveriesFreight carriers charges weight on the basis of Weight / volume of the items.SAP shipment works on the same principle.
Cost of transporting ton of Potataoes is same as transporting 10 ton of aluminium between two known destinations.
Hence it is illogical to distributes cost on the basis of item value. However if still you want to distribute the same on value basis then maintain freight condition(%) in PO as per your prefined logic of distribution of freight cost.
It is well known fact that cost of freight % is always higher in Low value items & iis low in case of High value items.
Regards,
Sanjay Kohli -
N9 Photo Gallery sort order - based on what?
Hello,
I am thrilled with my N9, but have one problem: I want to use the phone to keep not only photos made with it. I therefore saved extra photos in the Pictures folder. They appear in the gallery, but in a weird order, not based on either the name, EXIF date, modification date or creation date. Is there a possibility to sort them on either of these? All I want is to control the sort order. After all, it is MY gallery...
On my previous phone (N8) sorting was based on the last modification date. Also not optimal (EXIF date would have been perfect) but still controllable.
Solved!
Go to Solution.Well, maybe those pictures were never edited outside the phone, I don't know.
Anyway, I believe I found the explanation: I exported the photos from Picasa, maxing them to a resolution of 1600xXXX. This way all files were created... today. Nevertheless the EXIF information is correctly saved by Picasa, so Date Image Taken was preserved. Although I modified in all files the creation date to be equal to EXIF Date Image Taken (ACDSee/batch/AdjustTimeStamp) , and then also renamed all pictures based on that, the "new" creation date still remains saved somewhere in the picture files and the Gallery sorts the pictures on it! The pictures were sorted in the reversed order I exported them from Picasa... Bad.
Anyway, since this is not a request forum, it would be futile to say (again) that Nokia should use the EXIF Date Picture Taken for picture sorting. So I don't say it (!). -
F4 Help IN ALV (OOPs) based on value entered in Other colunm.
Hi,
I have developed a module pool using ALV GRID Display.
i have two fields in it. and for the second field i should provide F4 help. and the list in the f4 help should be based on the value enterd in first column.
below is my code.
MODULE BPO_100 OUTPUT.
DATA: LT_FCAT TYPE LVC_T_FCAT.
DATA: ls_fcat TYPE lvc_s_fcat.
DATA: wa type t_znout.
*DATA: it_kd1 LIKE zish_pm_cs_kd1fd OCCURS 0 WITH HEADER LINE.
SELECT * FROM zish_pm_cs_kd1fd INTO TABLE it_kd1 WHERE einri = rnpa1-einri.
IF sy-subrc = 0.
SORT it_kd1 BY sno.
ENDIF.
DELETE ADJACENT DUPLICATES FROM it_kd1 COMPARING fieldname.
LOOP AT it_kd1 into wa.
clear wa-value.
MODIFY it_kd1 FROM wa.
ENDLOOP.
ls_fcat-fieldname = 'FIELDNAME'.
ls_fcat-scrtext_l = 'Field name'.
ls_fcat-scrtext_m = 'Field name'.
ls_fcat-scrtext_s = 'Field name'.
ls_fcat-tabname = '1'.
ls_fcat-col_pos = '1'.
ls_fcat-outputlen = 15.
APPEND ls_fcat TO lt_fcat.
ls_fcat-fieldname = 'VALUE'.
ls_fcat-scrtext_l = 'Value'.
ls_fcat-scrtext_m = 'Value'.
ls_fcat-scrtext_s = 'Value'.
ls_fcat-tabname = '1'.
ls_fcat-col_pos = '2'.
ls_fcat-outputlen = 15.
ls_fcat-edit = 'X'.
ls_fcat-f4availabl = 'X'.
APPEND ls_fcat TO lt_fcat.
IF G_CUSTOM_CONTAINER1 IS INITIAL.
create a custom container control for our ALV Control
CREATE OBJECT g_custom_container1
EXPORTING
container_name = g_container1
EXCEPTIONS
cntl_error = 1
cntl_system_error = 2
create_error = 3
lifetime_error = 4
lifetime_dynpro_dynpro_link = 5.
IF sy-subrc ne 0.
add your handling, for example
CALL FUNCTION 'POPUP_TO_INFORM'
EXPORTING
titel = 'ZISH_SCRN_ALV'
txt2 = sy-subrc
txt1 = 'The control could not be created'(510).
ENDIF.
create an instance of alv control
CREATE OBJECT grid1
EXPORTING i_parent = g_custom_container1.
CALL METHOD grid1->set_table_for_first_display
EXPORTING
i_structure_name = 'ZISH_PA_ZNOUT'
i_default = gs_test_1700-vari_default
i_default = 'X'
i_save = gs_test_1700-vari_save
is_variant = ls_vari
is_layout = gs_layout1
CHANGING
it_outtab = it_kd1
IT_FIELDCATALOG = LT_FCAT.
ENDIF.
ENDMODULE. " BPO_100 OUTPUT
Edited by: Guru Ram on Sep 24, 2009 8:58 AMSee sample code.
I have 2 fields MATNR and DESC in screen 100. Change it according to ur needs.
In screen flow logic,
PROCESS ON VALUE-REQUEST.
FIELD desc MODULE module_desc. " F4 for screen field DESC based on value entered in field MATNR
In report,
MODULE module_desc INPUT.
TABLES: ddshretval.
DATA: l_t_dynpread LIKE dynpread OCCURS 0 WITH HEADER LINE,
l_t_dynpread1 LIKE dynpread OCCURS 0 WITH HEADER LINE.
DATA: l_t_retdynr TYPE TABLE OF ddshretval,
l_wa_retdynr LIKE LINE OF l_t_retdynr.
DATA: BEGIN OF g_t_desc OCCURS 0,
maktx TYPE makt-maktx,
END OF g_t_desc,
wa LIKE g_t_desc.
l_t_dynpread-fieldname = 'MATNR'. " Field1 name
APPEND l_t_dynpread.
CALL FUNCTION 'DYNP_VALUES_READ'
EXPORTING
dyname = sy-repid
dynumb = '0100'
TABLES
dynpfields = l_t_dynpread
EXCEPTIONS
invalid_abapworkarea = 1
invalid_dynprofield = 2
invalid_dynproname = 3
invalid_dynpronummer = 4
invalid_request = 5
no_fielddescription = 6
invalid_parameter = 7
undefind_error = 8
double_conversion = 9
stepl_not_found = 10
OTHERS = 11.
READ TABLE l_t_dynpread INDEX 1.
IF l_t_dynpread-fieldvalue IS NOT INITIAL.
CALL FUNCTION 'CONVERSION_EXIT_MATN1_INPUT' " Converting matnr to 18 digits
EXPORTING
input = l_t_dynpread-fieldvalue
IMPORTING
output = l_t_dynpread-fieldvalue.
SELECT maktx FROM makt INTO TABLE g_t_desc WHERE matnr = l_t_dynpread-fieldvalue.
CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
EXPORTING
retfield = 'MAKTX'
dynpprog = sy-repid
dynpnr = sy-dynnr
value_org = 'S'
TABLES
value_tab = g_t_desc
return_tab = l_t_retdynr
EXCEPTIONS
parameter_error = 1
no_values_found = 2
OTHERS = 3.
READ TABLE l_t_retdynr INTO l_wa_retdynr INDEX 1.
IF sy-subrc = 0.
l_t_dynpread1-fieldname = l_wa_retdynr-fieldname.
l_t_dynpread1-fieldvalue = l_wa_retdynr-fieldval.
APPEND l_t_dynpread1.
l_t_dynpread1-fieldname = 'DESC'. " Field2 name
APPEND l_t_dynpread1.
CALL FUNCTION 'DYNP_VALUES_UPDATE'
EXPORTING
dyname = sy-repid
dynumb = sy-dynnr
TABLES
dynpfields = l_t_dynpread1
EXCEPTIONS
invalid_abapworkarea = 1
invalid_dynprofield = 2
invalid_dynproname = 3
invalid_dynpronummer = 4
invalid_request = 5
no_fielddescription = 6
undefind_error = 7
OTHERS = 8.
ENDIF.
ENDIF.
ENDMODULE. " module_desc INPUT
Thanks. -
Sort Table based on Display Variant
Hi...
I want to Sort a table based on Display Variant Sort option??
Please Help????Hi Try this...
FM..
K_KKB_OUTTAB_SORT
To Sort Data
CALL FUNCTION 'K_KKB_OUTTAB_SORT'
EXPORTING
IT_SORT = I_SORT
TABLES
T_OUTTAB = I_MAIL_FINAL
EXCEPTIONS
SORTFIELD_NOT_FOUND = 1
OTHERS = 2.
IF SY-SUBRC <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF. -
Populating values in dropdown based on values selected in second dropdown.
Hi,
I have two listboxes on the screen. Based on value chosen in first dropdown, I want to populate the values to be selected in second dropdown. How can i achieve this? I would be glad if anyone can help me out with this requirement.
Thanks,
Ameet<font color=blue>Hi,
<li> Place 2 input fields on screen.
<li>Set Listbox property as it is shown in the below link.
<a href="http://2.bp.blogspot.com/_O5f8iAlgdNQ/SmPSPnRa0tI/AAAAAAAAFCQ/wW_URP-ld6o/s1600-h/drop_down-770536.JPG" target="_new">link to dropdown setting</a>
<li>Set function code to first dropdown box to trigger event when you select value from first dropdown box. So that second one is changed.
<li>Declare variable like below in TOP include of the module pool program.
<pre>DATA: g_drop_1 TYPE char10,
g_drop_2 TYPE char10,
ucomm TYPE sy-ucomm.
TYPE-POOLS vrm.
DATA: name TYPE vrm_id,
list TYPE vrm_values,
value LIKE LINE OF list.</pre>
<li> Use screen flow logic of the screen like below
<pre>"PROCESS BEFORE OUTPUT.
PROCESS BEFORE OUTPUT.
field g_drop_1 MODULE drop_down_1.
field g_drop_2 MODULE drop_down_2.
"PROCESS AFTER INPUT.
PROCESS AFTER INPUT.
field g_drop_1.
field g_drop_2.</pre>
<li>Corresponding code for two drop down boxes.
<pre>&----
*& Module DROP_DOWN_1 OUTPUT
MODULE drop_down_1 OUTPUT.
CLEAR: list[],g_drop_2.
name = 'G_DROP_1'.
value-key = '1'.
value-text = 'value_1'.
APPEND value TO list.
CLEAR value.
value-key = '2'.
value-text = 'value_2'.
APPEND value TO list.
CLEAR value.
value-key = '3'.
value-text = 'value_3'.
APPEND value TO list.
CLEAR value.
value-key = '4'.
value-text = 'value_4'.
APPEND value TO list.
CLEAR value.
CALL FUNCTION 'VRM_SET_VALUES'
EXPORTING
id = name
values = list.
ENDMODULE. " DROP_DOWN_1 OUTPUT
*& Module DROP_DOWN_2 OUTPUT
MODULE drop_down_2 OUTPUT.
CLEAR list[].
name = 'G_DROP_2'.
CASE g_drop_1.
WHEN 1 OR 2.
value-key = '1'.
value-text = 'text1'.
APPEND value TO list.
CLEAR value.
value-key = '2'.
value-text = 'text2'.
APPEND value TO list.
CLEAR value.
WHEN 3 OR 4.
value-key = '3'.
value-text = 'text3'.
APPEND value TO list.
CLEAR value.
value-key = '4'.
value-text = 'text4'.
APPEND value TO list.
CLEAR value.
ENDCASE.
CALL FUNCTION 'VRM_SET_VALUES'
EXPORTING
id = name
values = list.
ENDMODULE. " DROP_DOWN_2 OUTPUT</pre>
Thanks
Venkat.O</font> -
Sorting large amounts of data with treemap
Hello. Im doing a project where I have to sort a large amount of data. The data is formed by a unique number and a location (a string).
Something like this
NUMBER .... CITY
1000123 BOSTON
1045333 HOUSTON
5234222 PARIS
2343345 PARIS
6234332 SEATTLE
I have to sort the data by location and then by unique number...
I was using the TreeMap to do this : I used the location string as a key - since I wanted to sort the data by that field - but, because the location string is not unique, at the moment to insert the data on the TreeMap, it overwrites the object with the same location string, saving only the last one that was inserted.
Is there any Collection that implements sorting in the way that I need it?... or if there isnt such thing... is there any collection that supports a duplicated key object???
Thanks for your time!
Regards
Cesar... or use a SortedSet for the list of numbers (as the associated value for
the location key). Something like this:voidAddTuple(String location, Integer number) {
SortedSet numbers= set.get(location);
if (numbers == null)
set.put(location, numbers= new TreeSet());
numbers.put(number);
}kind regards,
Jos
Maybe you are looking for
-
Problems opening ical/iphoto/mail etc after restoring from time machine
hello everybody, hope you can help me!!! Problem... I got a new HardDisk installed in my Macbook from 2006. I made sure all the software was up to date an made a full backup on Time Machine before bringing it to the Mac Store. Back home i plugged it
-
Why does Oracle SQL query returning a date field without the time component
Hi, I'm a novice SQL user & hv just installed Oracle SQL developer (Version 3.0.04, Build MAIN-04.34). I made the same SQL query using "Oracle SQL developer" & "TOAD for Oracle 9.0.1" but I got 2 different format on the same date field: On TOAD, I ge
-
HT5824 how do I upload pictures to icloud
Can anyone tell me how I can upload pictures from my computer to icloud so I can back them up. Any help apreciated, thanks
-
Help me!!
-
HT4528 i accidentally restored my phone thru itunes I can't see messages
I want my phone back the way it was