Simplest way to loop through a HashMap?
Hi everyone,
I'm a beginner at JSP, so please excuse my ignorance...
I have a HashMap in which I need to loop through and print every "key" and associated "value".
Doing research, I have come across multiple examples, but they all seem (to me) rather complex for something I think should be simple.
Here is some code I have now. C_TITLE is a HashMap. My question is, is there an easier way to do this where I don't have to invoke a subclass? Or is this as simple and easy as it can get?
Thanks!
if (C_TITLE.size() > 0) { //only loop if there are items in this hashmap
for (Iterator i=C_TITLE.entrySet().iterator(); i.hasNext(); ) {
Map.Entry mapentry = (Map.Entry) i.next();
out.print (mapentry.getKey() + "|");
out.print (mapentry.getValue() + "<BR>\n");
}
Iteratir iter = C_TITLE.keySet().iterator();
while(iter.hasNext()) //or your for as well
Object key = iter.next();
Object value = C_TITLE.get(key);
}With J2SDK 1.5 there is new for loop to iterate through collections.
This will make Iterators almost unusable.
Similar Messages
-
Fastest way to loop through a group of strings
I am trying to optimize a small class that loops through an array of strings and compares to see if another string equals one of the values, for example:
String test = "this is test5";
String array[] = {"test1","test2","test3, test4,test5,test6,test7,test8"};
for(int i = 0;i < array.length; i++)
if (test.endsWith(array))
return array[i];
}The array that I am using holds closer to 15 values, but this loop can be hit thousands of times a day. My question is, are there any faster ways to loop through multiple strings than using arrays? How do array lists or maps compare?sarcasteak wrote:
The array that I am using holds closer to 15 values, but this loop can be hit thousands of times a day. 15,000 comparisons a day is nothing. The following code does 15 million String compares in 188 ms.
public class StrCmp {
public static void main(String... args) {
String[] arr = {"abc", "sdfasdlfkjasldfjalsdkfj", "234l2kjala34kh", "slkfjal3490u saf",
"234lkjasldfhk23k4jhasf", "23l4kjsf", "alsflsdjkf", "aslkdfajsdf3h", "zzzzz",
"uhuhuhuhuh", "uhu2huh234234", "n234aoiuf", "234lasdhvoaih3", "zoziucvoiu", "asdflsjfl"};
long start = System.currentTimeMillis ();
for (int i = 0; i < 1000000; i++) {
String str = "qqq";
for (String str2 : arr) {
if (str2.endsWith (str)) {
System.out.println ("match");
long end = System.currentTimeMillis ();
System.out.println((end - start) + " millis");
My question is, are there any faster ways to loop through multiple strings than using arrays? How do array lists or maps compare?Before you worry about taking something simple that works and complicating it to make it faster, make sure there's a reason to do so.
If you do in fact need to make it faster, there are several different things you could do, but which one is best depends on a number of factors specific to your particular requirements and use cases. -
What is the best way to loop through TextFlow to find InlineGraphicElements?
I have created a TextFlow and the images load fine, but I would like to loop through and update all the 'source' properties to change the images. What is the best way to locate all the InlineGraphicElements in my TextFlow?
Thanks!leaf = textflow.getFirstLeaf();
while( (leaf = leaf.getNextLeaf()) != null)
if(leaf is InlineGraphicElement) -
Most efficient way to loop through similarly named fields?
Hi,
I have a 5 page document with each page containing appx. 50 similarly named fields. E.g. Viol1Num, Viol2Num, Vio3Num ... Viol50Num.
I am looking for an efficient way of programming a loop to look at each field in Javascript so I can do some manipulations in those fields on what the user entered.
In FormCalc I've previously used the 'foreach' function similar to:
foreach (Field1, Field2, Field3.....Field50) do
'BLAH'
endfor
however, that gets really lengthy, especially when dealing with subsequent pages where I have to start adding 'topmostSubform.Page2.' in front of each field name so that I can access from the first page all of the fields on subsequent pages. Also, I need to do this in Javascript, not FormCalc.
For example, in JS I am using this loop to mark all fields as read only:
for (var nPageCount = 0; nPageCount < xfa.host.numPages; nPageCount++) {
var oFields = xfa.layout.pageContent(nPageCount, "field");
var nNodesLength = oFields.length;
for (var nNodeCount = 0; nNodeCount < nNodesLength; nNodeCount++) {
oFields.item(nNodeCount).access = "readOnly";
How could I do something similar to that so I could look through each field and perform actions on it without having to list out every single field name?
I tried altering that to look at fields instead of field properties, but I couldn't get it to run.
Thanks.I have solved my issue. It took some battling in javascript using xfa.resolveNode.
I have 5 pages, each consisting of a series of 60 fields named Viol1Num, Viol2Num, Viol3Num .... Viol60Num.
If when this javascript runs, it detects a blank field, then insert a '3' into it.
The below is the javascript which runs for the second page of this document.
while (LoopCounter < 61) {
if ((LoopCounter != 21) && (LoopCounter != 22)) {
if((xfa.resolveNode("topmostSubform.Page2.Viol" + LoopCounter + "Num").rawValue == null) | (xfa.resolveNode("topmostSubform.Page2.Viol" + LoopCounter + "Num").rawValue == "")) {
xfa.resolveNode("topmostSubform.Page2.Viol" + LoopCounter + "Num").rawValue = 3;
LoopCounter = LoopCounter + 1 -
Best way to loop through multiple rows to search for a count result
I have a script where I'm trying to find a Rollup row without any children. I have created a SQL statement to do this, but I can only input one point at a time. If the count is greater than 0 then i'm good to go. If the count is 0 then I want to know about it.
select count (*) from (Select * From ESSBASE_FCS.Ham
where hier_pt like (Select substr(hier_pt, 1,8)||'%' as hcy_pt
From ESSBASE_FCS.Ham
Where Hier_Pt = '412375....')
And Cctr_Or_Rollup 'Rollup')
What is the best way to develop a SQL script that searches through all my Hier_pt's and return everything with a count of 0, instead of manually inputing each hier_pt at a time?
Thanks for any help.Hi,
Please read SQL and PL/SQL FAQ
Please provide table structure, sample data and expected output.
Additionally when you put some code please enclose it between two lines starting with {noformat}{noformat}
i.e.:
{noformat}{noformat}
SELECT ...
{noformat}{noformat}
I noticed also that you have posted the same question here: {message:id=10678000}
If you move your question to another forum please mark the previous question as answered.
Regards.
Al
Edited by: Alberto Faenza on Nov 7, 2012 5:03 PM -
Loop through a csv file and return the number of rows in it?
What would be simplest way to loop through a csv file and
return the number of rows in it?
<cffile action="read" file="#filename#" output="#csvstr#"
>
<LOOP THROUGH AND COUNT ROWS>ListLen(). Use chr(13) as your delimiter
-
Hi,
Needed your inputs on approach to implement a job using dbms_scheduler.
We have around 2000 schemas. Each schema has a package with 2 procedures.
The requirement is to create a single job in SYS that would loop through each schema and run the procedures at a specific time ( once a day) and send email notification on success or failure.
Job script:
BEGIN
dbms_scheduler.create_job( job_name=> 'LOAD_EACH_SCHEMA_AUDIT_DATA',
job_type=>'PLSQL_BLOCK',
job_action=>'BEGIN sys.p_loadaudit;
END;',
start_date=>systimestamp,
repeat_interval=>'FREQ=MINUTELY;INTERVAL=1',
number_of_arguments=>0,
enabled=> true,
comments=>'Job repeat interval is every 5 mins' );
END;
Note: for testing purpose i have set repeat interval to minutely.
Procedure job will be executing:
Procedure sys.p_loadaudit:
CREATE OR REPLACE
PROCEDURE p_loadaudit
AS
v_count NUMBER:= 0;
lv_error_message VARCHAR2(4000);
vstmt VARCHAR2(4000);
BEGIN
FOR i IN
( SELECT username FROM dba_users WHERE username LIKE 'ABCFIRM%'
LOOP
vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_coa; end;';
EXECUTE immediate vstmt;
vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_am; end;';
EXECUTE immediate vstmt;
END LOOP;
EXCEPTION
WHEN OTHERS THEN
lv_error_message := 'Error in procedure p_loadaudit: ' || SQLCODE || ' -ERROR- ' || SUBSTR(
sqlerrm,1,300) || '*' || dbms_utility.format_error_backtrace;
raise_application_error(-20002,lv_error_message);
END p_loadaudit;
Example of one schema: SCHEMA_01
create or replace
PACKAGE pkg_audit_info
AS
type cursortype
IS
ref
CURSOR;
PROCEDURE p_load_COA;
PROCEDURE p_load_AM;
END pkg_audit_info;
create or replace
PACKAGE body pkg_audit_info
AS
PROCEDURE p_load_COA
AS
BEGIN
INSERT INTO TABLE1();
EXCEPTION
WHEN OTHERS THEN
lv_error_message := 'Error in procedure pkg_audit_info.p_load_COA: ' || SQLCODE
|| ' -ERROR- ' || SUBSTR(SQLERRM,1,300) || '*' || dbms_utility.format_error_backtrace;
RAISE_application_error(-20002,lv_error_message);
END p_load_COA;
PROCEDURE p_load_AM
AS
BEGIN
INSERT INTO TABLE2();
EXCEPTION
WHEN OTHERS THEN
lv_error_message := 'Error in procedure pkg_audit_info.p_load_AM: ' || SQLCODE ||
' -ERROR- ' || SUBSTR(SQLERRM,1,300) || '*' || dbms_utility.format_error_backtrace;
RAISE_application_error(-20002,lv_error_message);
END p_load_AM;
END pkg_audit_info;
Table1 and table1 exist in schema_01.
All 2000 schemas have same package.procedures.
Due to security reasons i have removed the actual code.
I was able to execute the job successfully. However, when a schema procedure (SCHEMA_01.pkg_audit_info.p_load_COA) throws an exception, the job fails and all transaction is rolled back.
Is there a way to loop through each schema and execute the related procedures. Even if exception happens, it should rollback only for that schema and continue the other schemas in the loop?
Please let me know if there is a better way to achieve this. Is the way i am handling exceptions in the job/procedure correct?
ThanksHi,
RAISE_APPLICATION_ERROR will cause the program to exit back to the caller, even if you place it in a block within the loop, so the RAISE or RAISE_APPLICATION_ERROR instruction should be placed in your "pkg_audit_info.p_load_AM" and "pkg_audit_info.p_load_coa" procedures. This way, you can use a block inside the loop and log the error.
FOR i IN
( SELECT username FROM dba_users WHERE username LIKE 'ABCFIRM%'
LOOP
BEGIN
vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_coa; end;';
EXECUTE immediate vstmt;
vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_am; end;';
EXECUTE immediate vstmt;
EXCEPTION
WHEN OTHERS THEN
--> Log the error in a custom log table otherwise you will not know what happened for that schema: don't forget the username
END;
END LOOP; -
Loop through tree node children recursively
Is there an easy way of looping through all the child nodes of a MutableTreeNode and the children of those children if they have any?
ThanksWith a recursive function (this is depth first):
public void traverse(Node node) {
// do something with node
for(Node child : node.getChildren()) {
traverse(child);
}You could also look at depthFirst/breathFirst/preorder/postorderEnumeration() methods on DefaultMutableTreeNode if that's what you actually got. -
Loop through all items in all data blocks?
Is there a way to loop through every item in every data block and set the property of a format mask?
I do not know what error it is, only that an on-error trigger fires.
I found out one thing I was definitely doing wrong, using nextblock, nextitem properties at the wrong level.
DECLARE
v_firstblock VARCHAR2(50);
v_currentblock VARCHAR2(50);
v_firstitem VARCHAR2(50);
v_currentitem VARCHAR2(50);
v_counter NUMBER :=0;
v_counter2 NUMBER :=0;
begin
v_firstblock := get_form_property(:System.Current_Form,first_block);
v_currentblock:= get_block_property(v_firstblock,nextblock);
MESSAGE(v_firstblock||v_currentblock);
LOOP
v_counter := v_counter +1;
IF (v_counter >10) THEN
exit;
END IF;
IF (v_currentblock = v_firstblock) THEN
exit;
ELSE
v_firstitem := get_block_property(v_firstblock,first_item);
IF (lower(GET_ITEM_PROPERTY(v_firstitem,format_mask))=lower('mm-dd-yyyy')) THEN
SET_ITEM_PROPERTY(v_firstitem,format_mask,'DD-MON-YYYY');
END IF;
v_currentitem := get_block_property(v_firstblock,first_item);
v_currentblock:= get_block_property(v_currentblock,nextblock);
GO_BLOCK(v_currentblock);
LOOP
v_counter2 := v_counter2 +1;
IF (v_counter2>15) THEN
exit;
END IF;
v_currentitem:= get_item_property(v_currentitem,nextitem);
MESSAGE(v_counter||v_firstblock||v_currentblock||v_firstitem||v_currentitem||v_counter2);
IF (v_currentitem <> v_firstitem) THEN
IF (lower(GET_ITEM_PROPERTY(v_currentitem,format_mask))=lower('mm-dd-yyyy')) THEN
SET_ITEM_PROPERTY(v_currentitem,format_mask,'DD-MON-YYYY');
END IF;
ELSE
exit;
END IF;
END LOOP;
END IF;
END LOOP;
end;Here is updated new code. I am currently trying to debug it, it has crashed my form on the server when tied to a button press.
EDIT: So far I have found that it infinitely loops through the first 3 items and a null item in the first block. Still looking into why...
EDIT: Some code changes to temporarily stop infinite loop and make v_currentblock actually change. Still loops through same 3 items in the first data block even though v_currentblock changes.
Edited by: 878576 on Oct 21, 2011 12:46 PM -
If I declare an array such as the one below.
declare
type array_type is table of varchar2(100) index by binary_integer;
component_array array_type;
begin
component_array(12345) := 'One';
component_array(12347) := 'Two';
component_array(12349) := 'Three';
for i in component_array.FIRST .. component_array.LAST
loop
dbms_output.put_line(component_array(i));
end loop;
end;Is there a way to loop through only the existing binary_integer indeces? For example, if you execute the block above, you'll get an error because the loop iteration is hitting 12346 which of course doesn't exist. Other than the workaround below, is there another way using any type of array method?
declare
type array_type is table of varchar2(100) index by binary_integer;
component_array array_type;
begin
component_array(12345) := 'One';
component_array(12347) := 'Two';
component_array(12349) := 'Three';
for i in component_array.FIRST .. component_array.LAST
loop
begin
dbms_output.put_line(component_array(i));
exception
when NO_DATA_FOUND then
null;
end;
end loop;
end;
Thanks.Hi,
Not to hijack this thread, but, since this is related to my answering OP's question, I am posting here.
How come this code is erroring out?
DECLARE
TYPE array_type IS TABLE OF VARCHAR2(100) INDEX BY VARCHAR2(1000);
component_array array_type;
BEGIN
component_array(12345) := 'One';
component_array(12347) := 'Two';
component_array(12349) := 'Three';
FOR i IN component_array.first .. component_array.last LOOP
IF component_array.exists(12345) THEN
dbms_output.put_line(component_array(i));
END IF;
END LOOP;
END;errors out with no_data_found, but, this doesn't ?
DECLARE
TYPE array_type IS TABLE OF VARCHAR2(100) INDEX BY VARCHAR2(1000);
component_array array_type;
BEGIN
component_array(12345) := 'One';
component_array(12347) := 'Two';
component_array(12349) := 'Three';
FOR i IN component_array.first .. component_array.last LOOP
IF component_array.exists(12344) THEN
dbms_output.put_line(component_array(i));
END IF;
END LOOP;
END;notice the static numbers in the .exists parameter.... -
Looping through lines in a jtextpane...?
Anyone know a smooth clean way to loop through the lines in a jtextpane? (in the document).
I need each line as String to do some checks on them...
Any help would be appreciated.I am doing something like:
Element map = doc.getDefaultRootElement();
int n = map.getElementCount();
for(int i=n; n >= 0; i--){
Element e = map.getElement(i);
// Now turn this element into a string.
try{
String line = doc.getText(e.getStartOffset(), e.getEndOffset()-e.getStartOffset());
}catch(BadLocationException ble){
System.out.println("Error in findTabWord()!");
}But interested in if there are any better (faster) ways of doing it. -
How to loop through dates using For Loop?
Hi All,
I assume the For Loop is the best way to loop through days in a date range, but I can't figure out how to add a day in the "AssignExpression" box. The following gets the errors "The expression contains unrecognized token 'DAY'",
and "Attempt to parse the expression 'DATEADD(DAY, 1, @CounterPlayer)' failed and returned error code 0xC00470A4."
InitExpression: @CounterPlayer = @DownloadFileDatePlayer
EvalExpression: @CounterPlayer <= @Today
AssignExpression: @CounterPlayer = DATEADD(DAY, 1, @CounterPlayer)
I need to step through days, not through files. What am I doing wrong here? I changed "DAY" to "Day," but that didn't fix it.
Thanks,
EricDOH! It just needed properly placed quotes. Here's the answer:
AssignExpression: @CounterPlayer = DATEADD("DAY", 1, @CounterPlayer) -
How to loop through columns of a table?
Hi, guys
Is there a way to loop through each column of a table? If there is a way, then how?
I have a table with columns of different datatypes , and I want to set default values for each column with a loop but don't know how to make it happen.
For example,
Table: Employees
declare
rec Employees%ROWTYPE;
begin
for col in rec.empno .. rec.location loop
if col = rec.empno then -- set default value for column empno;
end loop;
end;
/Sorry, I am a newbie to PL/SQL. Please help!
Thanks in advance.
Edited by: HappyJay on 2010/05/11 10:36Hi,
You can query the data dictionary views all_tab_columns (or user_tab_columns) to get the names of all the columns in a particular table.
Here's an easy way (but not a very efficient way) to loop through them:
SET SERVEROUTPUT ON
BEGIN
FOR c IN ( SELECT column_name
FROM all_tab_columns
WHERE owner = 'SCOTT' -- Remember ot use UPPER CASE inside quotes
AND table_name = 'EMP'
LOOP
dbms_output.put_line (c.column_name || ' = column_name inside loop');
END LOOP;
END;
/I'm confused about what you want to do, though.
Do you want the PL/SQL code to write and/or execute an ALTER TABLE command for each column? -
Loop through user text fields on a page
I am new to APEX and I have searched for an answer to this problem, but was not able to find one.
I have a page which has about 40 text boxes for user input. I would like to find a way to loop through all of the text boxes on the page when the user submits the form. I want to check the contents of each text box and filter out any characters that are not alpha or numeric. I would like to do this in one process. Is this possible? If so, how would I access the text boxes and remove the unwanted input? Could you please show me an example?
Thanks for any guidance on this.Hi,
I did not test this, but could something like after submit process work
DECLARE
l_temp VARCHAR2(32000);
BEGIN
FOR C IN
(SELECT item_name
FROM apex_application_page_items
WHERE display_as = 'Text Field'
AND application_id = :APP_ID
AND page_id = :APP_PAGE_ID
LOOP
-- Do stuff e.g. remove character Ö
l_temp := REPLACE(v(c.item_name),'Ö');
APEX_UTIL.SET_SESSION_STATE (
p_name => c.item_name,
p_value => l_temp
END LOOP;
END;Br,Jari
Edited by: jarola on Mar 4, 2010 5:26 PM -
Looping through records... LC 8.0
Hi there
It seems easy enough to get the first record from a DB into a Form - but for the life of me I cannot find a way to loop through all the records (like mail merge) and enter all the records?
Could someone please point me in the right direction?
ThanksHi Paul
That method would appear to be dependent upon a click method with buttons.
Apart from the fact that it is time consuming, I can get the end result using .NET and iTextSharp (or ActivePDF Toolkit in asp.NET) to produce 'bulk' pdf documents by loading everything into a DataTable and running through a For loop for each row in the DataTable.
These forms would be a 'one off' for each new Customer, with an average of 120 records, so was looking for a 'quick and dirty' approach - as you may gather we have LC but not used it very much at all, so perhaps I was missing something!
Maybe you are looking for
-
So far so good I like the OS as I did Windows 8.1
So far so good. I like the OS being a Windows 8 beta tester, now makes me really appreciate the finer quality of 10. Really great. Setup went well, devices were Windows 8 ready, hardware installed automatically directly from the OEM manufacture, such
-
Delete job failed in IDOC archiving
Hi Gurus Delete job for IDOC archiving failed with the following error. "Job started Step 001 started (program RSEXARCD, variant PROD_DELETE, user ID CTMBATCH) Archive file 002558-001IDOC is being verified Operating system message: Permission denied
-
How do I cancel a "pending" payment?
My payments kept not working - now I see I have 8 "pending" payments! If they all go through I will be broke, how can you cancel these stupid things? One message said I have a different paypal linked to my account, but I can't see where I can change
-
Older iMAc, OS X 10.8.5 and WIFI
Hello, I updated from 10.6.8 to 10.8.4 a couple of weeks ago. Everything's running smoothly. However, having read in these forums that updating further to 10.8.5 knocks out the WIFI connection ( on which I'm using my Mac ) for older models with 802.
-
Return of the Deathstar !
Hi, I'm replacing an IMB deskstar within my G4 before it finally implodes and before swapping it out I'm obviously trying to back it up in order to restore to the new HD once installed. There are three files that both Silverkeeper and Carbon Copy Clo