Iterate thru a HashMap() to view its keys and values
I need to iterate over the hashmap to view its keys and values
but the hashmap in 1.5 doesnt return itearor
is there another way to view the key and value in the hashMap
HashMap<String, Integer> colMap = new HashMap<String, Integer>();
String[] array = { "Internal", "Transfer ", "Settle", };
List<String> colnames = Arrays.asList(array);
for (int i = 0; i < cols; i++) {
if (colnames.contains(headers.get(i))) {
colMap.put(headers.get(i), new Integer(i));
// I need to iterate over this map to get key and values
// The code below doesnt give me the key and values
for (Iterator iter = colMap.iterator(); iter.hasNext();)
Map.Entry entry = (Map.Entry)iter.next();
String key = (String)entry.getKey();
String value = (String)entry.getValue();
Maps provide methods called keySet(), values() and entrySet(). Each of those returns a Collection (Set/Collection/Set respectively) that represents a view on the Map. You can get those and get a iterator of that objects.
If you need both the key and the value in a loop, then you should use the entrySet method.
Similar Messages
-
HashMap keys and values not staying consistent (my fault, but why?)
Alright, after starting out for the very first time with HashMaps a few hours ago, I've gotten the hang of them decently I think. I am encountering a problem, though, when I try to get user-selected keys + values to display. My code is:
public void useZone(String use)
Object used = hm.get(use);
System.out.print("\f");
Set set = hm.entrySet();
Iterator i = set.iterator();
if (used != null){
System.out.println("Time Zone Used:");
Map.Entry thiszone = (Map.Entry)i.next();
Object usedzone = thiszone.getValue(); //Get the value of the zones and assign them as Object usedzone
Integer useval = (Integer) usedzone; //Assign the Object to an Integer value so we can use it
difference = useval;
if (useval > 0){ //Display the hour offset correctly
System.out.println(use + ": GMT +" + usedzone.toString());
else if (useval == 0){
System.out.println(use + ": GMT");
else if (useval < 0){
System.out.println(use + ": GMT " + usedzone.toString());
else{
System.out.println("Invalid zone name.");
} //End if
ClockDisplay.getZone(difference); //Send variable difference
}What will happen is that the first time I will be fine...
Say the HashMap keys and values are
"Rome", "-2"
"Chicago", "6"
"New York", "5"
"Paris", "-1"
If I type "Rome" in when I execute this method, it gives me the correct output - "Rome: GMT -2"
If I then re-run the method, as to display a different one, I get "Chicago: GMT -2"
It's like the name the user inputs is updating, obviously, but the value of the HashMap that goes along with the user-input doesn't match up or something. My code is confusing myself after looking at it for nearly 10 hours, so I apologize that I had to post something so trivial here - I'm sure it's just a problem with my wordings....any help would be greatly appreciated.Hello,
It's very possible I'm missing some things here, but I've attempted to review your code.
Let me just define the specs of the code as I see them:
Method useZone accepts String input, which is "supposed" to be the key to a hashmap.
The timezone offsets are the value's in this hashmap.
The value is of type Integer.
If a key is properly selected, print out GMT + or - the offset?
If I have this correct, consider the following implementation:
public void useZone(String use) {
Integer offset = (Integer)hm.get(use);
System.out.print("\f");
if (offset != null){
System.out.println("Time Zone Used:");
System.out.println(use + ": GMT +" + offset.toString());
} else{
System.out.println("Invalid zone name.");
ClockDisplay.getZone(offset); //Send variable difference
}I'd guess you're getting odd behavior because you're creating an iterator to iterate through the map, but then only calling i.next() once - HashMap doesn't guarantee insertion order, so the fact it worked once correctly is "random".
Also, if you are using java 1.5 declare the map as follows:
Map<String, Integer> hm = new HashMap<String, Integer>();And you can get rid of the casts. I would also suggest renaming the hashmap to something that describes what it holds, rather than it's object type. Maybe something like timeZoneMap - or offsetMap. I would also consider renaming "use" to something that describes the data it might hold, instead of something that describes the workflow.
Variable naming is very difficult! I would suggest renaming all of your variables, but I think those are the only ones I kept!
Edited by: Adam_Schaible on Nov 28, 2007 12:09 PM -
Why does HashMap.java use transient for the collection of key and value?
I just took a look at source code of HashMap.java.
It uses the variable "table" to store the keys and values.
This vairalbe is transient, but any hashmap can be serialized and deserialized.
Could you please help me clarify how it could happen that the transient variable can be serialized?The 'table' might be transient, but its content, or current data content of the map, shoud be somehow saved/restored in the serializing/deserializing code of the HashMap.
-
Please Help::How to display a Map with LIsts as Keys and Values using JSTL
Hi,
I need some assistance on how to display a Map in JSP using struts or core JSTL. I have a HashMap which has a List of keys and each key maps to a value of an ArrayList.i.e I have an ArrayList of taxCodes and each taxCode maps to a value of taxDetails which is an ArrayList of details for for that particular taxCode. I have some trouble to display each taxCode then display taxDetails for each taxCode. Here is my code below:
OrderDetails.java
package orderitems;
import java.sql.*;
import java.util.*;
public class OrderDetails {
private LineOder lineOrder;
private Map lineItems;
//returns an item number, key_item, from its unique keys
public int getItemNumber(int key_item, String key_year,
String key_office,String key_client,String key_company){
Connection conn = null;
Statement stat = null;
ResultSet rst = null;
int itmNum = 0;
* key_item a unique number for an item.
* key_year,key_office,key_client,key_company unique keys
* for each order where this key_item is taken
* from.
String select = "SELECT key_item FROM "+
Constants.WEB_TABLE +" WHERE key_item = " + key_item +
" AND key_year = '" + key_year + "'" +
" AND key_office = '" + key_office + "'" +
" AND key_client = '" + key_client + "'" +
" AND key_company = '" + key_company +"'";
DbConnection dbConn = new DbConnection();
try {
conn = dbConn.getDbConnection(Constants.WEB_JNDI);
stat = conn.createStatement();
rst = stat.executeQuery(select);
if(rst.next()){
itmNum = Integer.parseInt(rst.getString("key_item"));
} catch (SQLException ex) {
ex.printStackTrace();
} finally{
SQLHelper.cleanUp(rst, stat, conn);
return itmNum;
//get a list of item number(item codes)
public List getAllItemNumbers(String key_year,
String key_office,String key_client,String key_company){
List itemNumbers = new ArrayList();
LineItem itemNumber = null;
Connection conn = null;
Statement stat = null;
ResultSet rst = null;
String select = "SELECT key_item FROM "+ Constants.WEB_TABLE +
" WHERE key_year = '" + key_year + "'" +
" AND key_office = '" + key_office + "'" +
" AND key_client = '" + key_client + "'" +
" AND key_company = '" + key_company + "'";
DbConnection dbConn = new DbConnection();
try {
conn = dbConn.getDbConnection(Constants.WEB_JNDI);
stat = conn.createStatement();
rst = stat.executeQuery(select);
while(rst.next()){
itemNumber = new LineItem();
itemNumber.setKey_item(Integer.parseInt(rst.getString("key_item")));
itemNumbers.add(itemNumber);
} catch (SQLException ex) {
ex.printStackTrace();
} finally{
SQLHelper.cleanUp(rst, stat, conn);
return itemNumbers;
//get a list of tax codes
public List getAllTaxCodes(int key_item, String key_year,
String key_office,String key_client,String key_company){
Connection conn = null;
Statement stat = null;
ResultSet rst = null;
ItemTax taxCode;
List taxCodes = new ArrayList();
int itemNum = getItemNumber(key_item, key_year,
key_office,key_client,key_company);
String select = "SELECT key_tax_code FROM "+
Constants.WEB_TABLE +" WHERE key_item = " + itemNum +
" AND key_year = '" + key_year + "'" +
" AND key_office = '" + key_office + "'" +
" AND key_client = '" + key_client + "'" +
" AND key_company = '" + key_company +"'";
DbConnection dbConn = new DbConnection();
try {
conn = dbConn.getDbConnection(Constants.WEB_JNDI);
stat = conn.createStatement();
rst = stat.executeQuery(select);
while(rst.next()){
taxCode = new ItemTax();
taxCode.setKey_tax_code(rst.getString("key_tax_code"));
taxCodes.add(taxCode);
} catch (SQLException ex) {
ex.printStackTrace();
} finally{
SQLHelper.cleanUp(rst, stat, conn);
return taxCodes;
/////This methode returns a Map which am trying to display in JSP
//use tax code to get tax details
public Map getItemTaxDetails(String key_year,String key_office,
String key_client,String key_company,int key_item){
ItemTax taxDetail = null;
List taxDetails = new ArrayList();
List itemTaxCodes = new ArrayList();
Map itemTaxDetails = new HashMap();
Connection conn = null;
Statement stat = null;
ResultSet rst = null;
//get a list of all tax codes of an item with a
//given item number
itemTaxCodes = getAllTaxCodes(key_item,key_year,
key_office,key_client,key_company);
DbConnection dbConn = new DbConnection();
try {
conn = dbConn.getDbConnection(Constants.WEB_JNDI);
stat = conn.createStatement();
for(Iterator taxCodeIter= itemTaxCodes.iterator(); taxCodeIter.hasNext();){
ItemTax itemTaxCode = (ItemTax)taxCodeIter.next();
String taxCode = itemTaxCode.getKey_tax_code();
String select = "SELECT tax_type,tax_value," +
"tax_limit_val FROM "+ Constants.WEB_TABLE +
" WHERE key_item = "+ key_item +
" AND key_year = '" + key_year + "'" +
" AND key_office = '" + key_office + "'" +
" AND key_client = '" + key_client + "'" +
" AND key_company = '" + key_company +"'" +
" AND key_tax_code = '" + taxCode + "'";
rst = stat.executeQuery(select);
while(rst.next()){
taxDetail = new ItemTax();
//records to be displayed only
taxDetail.setKey_item(Integer.parseInt(rst.getString("key_item")));
taxDetail.setTax_value(rst.getString("tax_value"));
taxDetail.setTax_limit_val(Float.parseFloat(rst.getString("tax_limit_val")));
//////other details records ommited//////////////////////////
taxDetails.add(taxDetail);////An ArrayList of taxDetails for each taxCode
* A HashMap which has all taxCodes of an item as its keys
* and an ArrayList of taxdetails as its values.
* I return this for display in a JSP.
itemTaxDetails.put(taxCode,taxDetails);
System.out.println();
System.out.println("*********CONSOLE OUTPUT*************");//display on console
Set set = itemTaxDetails.keySet();
Iterator iter = set.iterator();
System.out.println("Key\t\tValue\r\n");
while (iter.hasNext()) {
Object taxCode=iter.next();
Object details=itemTaxDetails.get(taxCode);
System.out.println(taxCode +"\t" + details);
System.out.println("************************************");
} catch (SQLException ex) {
ex.printStackTrace();
} finally{
SQLHelper.cleanUp(rst, stat, conn);
return itemTaxDetails;
//details of an item with all its taxes
public List getAllItemDetails(String key_year,
String key_office,String key_client,String key_company){
List lineItems = new ArrayList();
List itemNumbers = new ArrayList();
Map taxDetails = new HashMap();
LineItem item = null;
Connection conn = null;
Statement stat = null;
ResultSet rst = null;
//A list of all item numbers in the declaration
itemNumbers = getAllItemNumbers(key_year,
key_office,key_client,key_company);
DbConnection dbConn = new DbConnection();
try {
conn = dbConn.getDbConnection(Constants.WEB_JNDI);
stat = conn.createStatement();
for(Iterator itemIter= itemNumbers.iterator(); itemIter.hasNext();){
LineItem itemNum = (LineItem)itemIter.next();
int itemNumber = itemNum.getKey_item();
String select = "SELECT item_description,item_mass," +
"item_cost" +
" FROM " + Constants.WEB_TABLE +
" WHERE key_year = '"+key_year+"'" +
" AND key_office = '"+key_office+ "'"+
" AND key_client = '"+key_client+ "'"+
" AND key_company = '"+key_company+ "'"+
" AND key_item = " + itemNumber;
rst = stat.executeQuery(select);
while(rst.next()){
item = new LineItem();
item.setItem_description(rst.getString("item_description"));
item.setItem_mass(Float.parseFloat(rst.getString("item_mass")));
item.setKey_item(Integer.parseInt(rst.getString("item_cost")));
//////other details records ommited//////////////////////////
/* A HashMap of all itemTaxeCodes as its keys and an
* ArrayList of itemTaxedetails as its values
taxDetails = getItemTaxDetails(item.getKey_year(),item.getKey_office(),
item.getKey_client(),item.getKey_company(),item.getKey_item());
//item tax details
item.setItmTaxes(taxDetails);
//list of items with tax details
lineItems.add(item);
} catch (SQLException ex) {
ex.printStackTrace();
} finally{
SQLHelper.cleanUp(rst, stat, conn);
return lineItems;
public Set getOrders(String key_year,String key_office,
String key_client,String key_company){
List lineItems = new ArrayList();
Set lineOrders = new HashSet();
Connection conn = null;
Statement stat = null;
ResultSet rst = null;
LineOder lineOrder = null;
String select = "SELECT * FROM " + Constants.WEB_TABLE +
" WHERE key_year = '" + key_year + "'" +
" AND key_office = '" + key_office + "'" +
" AND key_client = '" + key_client + "'" +
" AND key_company = '" + key_company + "'";
DbConnection dbConn = new DbConnection();
try {
conn = dbConn.getDbConnection(Constants.WEB_JNDI);
stat = conn.createStatement();
rst = stat.executeQuery(select);
while(rst.next()){
lineOrder = new LineOder();
lineOrder.setKey_year(rst.getString("key_year"));
lineOrder.setKey_office(rst.getString("key_office"));
lineOrder.setKey_client(rst.getString("key_client"));
lineOrder.setKey_company(rst.getString("key_company"));
////list of items with all their details
lineItems = getAllItemDetails(lineOrder.getKey_year(),lineOrder.getKey_office(),
lineOrder.getKey_client(),lineOrder.getKey_company());
//setting item details
lineOrder.setItems(lineItems);
//a list of order with all details
lineOrders.add(lineOrder);
} catch (SQLException ex) {
ex.printStackTrace();
} finally{
SQLHelper.cleanUp(rst, stat, conn);
return lineOrders;
Controller.java
package orderitems;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Controller extends HttpServlet {
private Map taxDetails = new HashMap();
private OrderDetails orderDetails = null;
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String key_year = "2007";
String key_office = "VZX00";
String key_company = "DG20";
String key_client = "ZI001";
int key_item = 1;
String nextView = "/taxdetails_list.jsp";
orderDetails = new OrderDetails();
taxDetails = orderDetails.getItemTaxDetails(key_year,key_office,
key_company,key_client,key_item);
//Store the collection objects into HTTP Request
request.setAttribute("taxDetails", taxDetails);
RequestDispatcher reqstDisp =
getServletContext().getRequestDispatcher(nextView);
reqstDisp.forward(request,response);
protected void doGet(HttpServletRequest request,
HttpServletResponse response)throws
ServletException, IOException {
processRequest(request, response);
protected void doPost(HttpServletRequest request,
HttpServletResponse response)throws
ServletException, IOException {
processRequest(request, response);
taxdetails_list.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Simple Tax Detail Diaplay ::</title>
<link rel="stylesheet" type="text/css" href="imgs/orders.css"/>
</head>
<body>
<jsp:useBean id="taxDetails" class="java.util.HashMap" scope="request"/>
<table>
<c:forEach items="${taxDetails}" var="hMap">
<tr>
<td><c:out value="${hMap.key}" /></td>
<!--td><%--c:out value="${hMap.value}" /--%></td-->
</tr>
</c:forEach>
</table>
</body>
</html>am displaying taxCodes(in this case i have VAT and ICD) fine but cant figure out how to display a list of value for each taxCode.Here is the output am getting
both in my JSP and on the console:
*******************************CONSOLE OUTPUT****************************
Key Value
ICD [orderItems.ItemTax@13e6226, orderItems.ItemTax@9dca26]
VAT [orderItems.ItemTax@13e6226, orderItems.ItemTax@9dca26]
Edited by: aiEx on Oct 8, 2007 6:54 AMhi evnafets,
yes i need a nested for loop.I have tried your advice but my bean properties are not found.Am getting this error:
javax.servlet.ServletException: Unable to find a value for "key_item" in object of class "java.lang.String" using operator "."
I have tried this as stated earlier in the post:I have tried to make the method getItemTaxDetails return a List and get the returned list value as taxDetails. I then tested to display this list on JSP and its displaying fine.
public List getItemTaxDetails(String key_year,String key_office,
String key_client,String key_company,int key_item){
ItemTax taxDetail = null;
List taxDetails = new ArrayList();
List itemTaxCodes = new ArrayList();
Map itemTaxDetails = new HashMap();
Connection conn = null;
Statement stat = null;
ResultSet rst = null;
//get a list of all tax codes of an item with a
//given item number
itemTaxCodes = getAllTaxCodes(key_item,key_year,
key_office,key_client,key_company);
DbConnection dbConn = new DbConnection();
try {
conn = dbConn.getDbConnection(Constants.WEB_JNDI);
stat = conn.createStatement();
for(Iterator taxCodeIter= itemTaxCodes.iterator(); taxCodeIter.hasNext();){
ItemTax itemTaxCode = (ItemTax)taxCodeIter.next();
String taxCode = itemTaxCode.getKey_tax_code();
String select = "SELECT tax_type,tax_value," +
"tax_limit_val FROM "+ Constants.WEB_TABLE +
" WHERE key_item = "+ key_item +
" AND key_year = '" + key_year + "'" +
" AND key_office = '" + key_office + "'" +
" AND key_client = '" + key_client + "'" +
" AND key_company = '" + key_company +"'" +
" AND key_tax_code = '" + taxCode + "'";
rst = stat.executeQuery(select);
while(rst.next()){
taxDetail = new ItemTax();
//records to be displayed only
taxDetail.setKey_item(Integer.parseInt(rst.getString("key_item")));
taxDetail.setTax_value(rst.getString("tax_value"));
taxDetail.setTax_limit_val(Float.parseFloat(rst.getString("tax_limit_val")));
//////other details records ommited//////////////////////////
taxDetails.add(taxDetail);////An ArrayList of taxDetails for each taxCode
* A HashMap which has all taxCodes of an item as its keys
* and an ArrayList of taxdetails as its values.
* I return this for display in a JSP.
itemTaxDetails.put(taxCode,taxDetails);
} catch (SQLException ex) {
ex.printStackTrace();
} finally{
SQLHelper.cleanUp(rst, stat, conn);
//return itemTaxDetails;
return taxDetails;
}And my JSP
taxdetails_list.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="imgs/orders.css"/>
</head>
<body>
<table>
<c:forEach var="curRecord" items="${taxDetails}" varStatus="rowCounter">
<c:choose>
<c:when test="${rowCounter.count % 2 == 0}">
<c:set var="rowStyle" scope="page" value="odd" />
</c:when>
<c:otherwise>
<c:set var="rowStyle" scope="page" value="even" />
</c:otherwise>
</c:choose>
<tr class="${rowStyle}">
<td>${curRecord.key_item}</td>
<td>${curRecord.tax_value}</td>
<td>${curRecord.tax_limit_val}</td>
</tr>
</c:forEach>
</table>
</body>
</html>I can't see where am going wrong even with your advice.Please help.
Thnx. -
How to set PropertyBag Key and value at farm and sitecollection via PowerShell
Hi,
how could i create PropertyBag Key and value at farm and sitecollection via PowerShell?
Best Regards
Bog
Developers Field Notes | www.bog1.deHey, you can do it as follows
asnp *sh*
$site = get-spsite "site url"
$web = $site.openweb()
$web.AllProperties["NEW KEY"] = "NEW VALUE"
$web.update()
$web.dispose()
Your new custom property will be present in the web Property bag.
and you can access it by $web.AllProperties["New Key"] or simply $web.Properties["New Key"]
get2pallav
Please click "Propose As Answer" if this post solves your problem or "Vote As Helpful" if this post has been useful to you. -
Writing the hashtable content (both keys and values) into a text file
Hello,
I have a hashtable which have some keys and respective values in it. Now I want to write all thoses content into a text or log file. Can anyone please tell me how to write it.
thanks,
chaitanyaProperties is a subclass of Hashtable. It'll probably work just fine as a drop-in replacement.
Otherwise...if all keys and values are text, then loop through the Entry objects in the Map in question (Hashtable is a Map, and you probably shouldn't be using Hashtable anyway), or loop through the keys and grab the corresponding value for the keys. Read the API docs for java.util.Map. It's pretty straightforward. -
My cluster application needs to do some bidirectional mappings via coherence between
coherence members and application entities.
What we have now are mappings that use Member.getID() integers.
When we need to dispatch logic to Members hosting an entity
we'll use InvocableService.{execute,query}() with a member set derived by use of
ServiceInfo.getServiceMember() for the int member ID's we have.
My concern is that if we have delays or other snafus in membership event processing
that the member id's returned by getID() will be recycled and refer to a different cluster member.
For example, if our event listener is down for some time, when it comes back up there may be
entries in the cache whose member ID's were recycled, at least that's my fear.
For our logic that would be bad. We'd assume we had entity assignment to a member
that has actually disappeared.
I could potentially use Member.getUID(), but that doesn't guarantee a unique
identifier, and so like a hash I wouldn't use it as the sole key where an unambiguous
resolution is required.
I was just looking for advice on anternatives or pitfalls of having caches
keyed or valued by cluster Members in whatever way works best.
We have a set of resources where want to apply our own membership distribution policies
according to a complex algorithm applied to whatever the cluster topology du jour may be,
so just allowing coherence maps to do the partitioning for us is not an option in this case.I haven't had any problems with it yet, but the facility is still in development.
Being armed with a bit more information now can save a lot of headaches later.
The information you provided should be enough to help me avoid problems.
The only issue for me being that we're still running version 3.5, but presumably the UID format
you described was the same in 3.5 too.
Thanks much! -
Binary Tree Implementations - why both key and value?
Hi there!
I'm sitting here implementing a binary tree, and I was just wondering why most of the binary tree examples encapsulate both a key AND a value in their nodes. Wouldn't it be sufficient to just store comparable objects in the nodes (or provide a comparator for alternative ordering)?
Thanks again, Oliver
P.S.:Any suggestions on good books (free E-Books preferred :-)) on ADTs and algorithms? I'm reading 'Data Structures And Algorithms In Java' by Robert Lafore and not very happy with it (the examples are just plain awful).Trollhorn wrote:
Hi there!
I'm sitting here implementing a binary tree, and I was just wondering why most of the binary tree examples encapsulate both a key AND a value in their nodes. Wouldn't it be sufficient to just store comparable objects in the nodes (or provide a comparator for alternative ordering)?Yes.
Thanks again, Oliver
P.S.:Any suggestions on good books (free E-Books preferred :-)) on ADTs and algorithms? I'm reading 'Data Structures And Algorithms In Java' by Robert Lafore and not very happy with it (the examples are just plain awful).As online resources:
[http://www.cs.princeton.edu/introcs/44st/]
[http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-006Spring-2008/CourseHome/index.htm]
I don't know of any eBooks on the subject, but I can recommend an excellent hard copy book:
Introduction To Algorithms, by Cormen et al. [http://highered.mcgraw-hill.com/sites/0070131511/information_center_view0/] -
I have a long document and I want to be able to search for certain key words and phrases, and then see how many times they appear in the document and exactly where. How do I conduct this sort of search and viewing? In the past, in Pages and Word, I've been able to view my "finds" in a sidebar but I can't figure out how to activate that service anymore.
Thanks!Here is a word frequency concordance Automator Service that works in both versions of Pages. It does not present a page number reference. It is by descending count, and alphabetically, within the repetitive counts as shown in the image here. In any document, you select the text to process, then Menu > Application Name > Services > Frequency. The Service will open TextEdit with the n-pages of scrollable results. It is 16 pt Helvetica Neue for legibility.
Here is the code:
on run {input, parameters}
try
set mySelection to input as text
set formatted_result to concordance(mySelection)
if formatted_result is not null then
set textHeading to "Word Frequency List"
tell application "TextEdit"
activate
set NewDoc to make new document with properties {name:"Concordance"}
make new paragraph at beginning of text of NewDoc with data textHeading & return
make new paragraph at end of text of NewDoc with data formatted_result
tell text of NewDoc
set font to "Helvetica Neue"
set size to 16
set color of paragraph 1 to {0, 0, 65535}
end tell
end tell
else
display dialog with title ¬
"No input selected" with icon stop ¬
giving up after 15
end if
on error errmsg number errnum
display alert ¬
"AppleScript Error" message errmsg & "[" & errnum & "]" as critical ¬
giving up after 30
end try
return input
end run
on concordance(mySelection)
-- Use Ruby to count word frequency and alphabetically sort words
set rb to ¬
"selected = String.new\nfreqs = Hash.new(0)\nselected = ARGV.join(' ').gsub(/[,.]/, \"\")\n
words = selected.split(/[^\\w-]+/)\nwords.each { |word| freqs[word] += 1 }\n
freqs_sorted = freqs.sort do |a,b|\n\t
a.last == b.last ? a.first <=> b.first : b.last <=> a.last\nend\n
freqs_sorted.each { |k,v| printf \"[ %8s ] %s\", v, k }"
do shell script "/usr/bin/ruby -e " & rb's quoted form & space & mySelection's quoted form
end concordance
Launch /Applications/Automator and choose New Document, then click the Service icon, and then select the Choose button.
On the left, you will have a list of Libraries from which to choose workflow items. Find Library > Utilities. In the adjacent column, locate the Run Applescript workflow. Click on it, then drag and drop it in the large workflow window to your right.
At the top, you can select Service receives text in any application. Leave Output replaces selected text unchecked.
In your Run AppleScript workflow window, you will see AppleScript boilerplate. Click on it and press command+A, then backspace to delete this content. Copy and paste the above code into this Run AppleScript workflow window. Press the Run button in Automator's upper right corner. If (and it should) a TextEdit window pops up, you are good, and you want to press File > Save. A dialog box will pop-up where you can name your Service. I called my Frequency, you may wish to call it something else. Once you have save it, you can exit Automator. Services are deposited in yourlogin directory/Library/Services.
If you have a Pages document open with text, either select it, or command+a to select the entire document. Now, you select your Service via Pages > Services > Frequency. This will now pop-up a new TextEdit document with the results. If you want to save this new document, you must use option+File to Save as... -
WD for Java: How to I retrieve key and value for DropDownbyKey selection
Dear All
I thought this was going to be straightfoward and am obviously missing something.
I have created a simple modifiable value set to create a dropdown list to select a country:
public void GetCountryDropDownValues( )
//@@begin GetCountryDropDownValues()
Y_Tf_Npf_Get_Countries_Input countriesInput = new Y_Tf_Npf_Get_Countries_Input();
wdContext.nodeY_Tf_Npf_Get_Countries_Input().bind(countriesInput);
try {
countriesInput.execute();
wdContext.nodeY_Tf_Npf_Get_Countries_Input().nodeOutput_countries().invalidate();
} catch (WDRFCException ex) {
// TODO: handle exception
IPrivateNonPersonalisedLearnAdminReq.IContextElement elem = wdContext.currentContextElement();
String strObjElem0 = elem.COUNTRY;
IWDAttributeInfo i_ObjType0 = wdContext.getNodeInfo().getAttribute(strObjElem0);
ISimpleTypeModifiable w_ObjType0 = i_ObjType0.getModifiableSimpleType();
IModifiableSimpleValueSet s_ObjType0 = w_ObjType0.getSVServices().getModifiableSimpleValueSet();
s_ObjType0.clear();
for(int i=0;i<wdContext.nodeEt_Countries().size();i++)
IPublicNonPersonalisedLearnAdminReq.IEt_CountriesElement elemOrg = wdContext.nodeEt_Countries().getEt_CountriesElementAt(i);
s_ObjType0.put(elemOrg.getLand1(),elemOrg.getLandx50());
//@@end
This is bound to a new context element attribute:
Country of type string
When value is selected from dropdown, it is stored in string
What I want to be able to do is to retrieve the text as well as the key from the selected object.
At the moment I can only return the key.
i.e. wdContext.currentContextElement().getCountry();
Any pointers will be greatfully received and maximum points awarded to the first complete
answer that works for me.
Many thanks in advance
MikeHi,
You can use the following code.
ISimpleValueSet valueset = attInfo.getModifiableSimpleType().getSVServices().getValues();
if(valueset.containsKey(key)){ // Give your key here, which you already know to retrieve
String value = valueset.getText(key); // Here you will get the value
Hope it helps.
Regards,
Manoj -
Error message display both key and value
Hi,
I've an alt key check & if the validation fails then the error message pops-up and displays :
Error
JBO-SUB_TYPE_CODE_ALREADY_EXIST: The sub type code already exists.
I'm not sure why is it displaying the key (JBO-SUB_TYPE_CODE_ALREADY_EXIST:) part also in the message.
Can someone tell me how to suppress the key part in the error message and just display the message (The sub type code already exists.).
Thanks,
-GauravHi,
If you want to avoid the roundtrip to the database you can also create a uniqueKey validator in the Entity Object
were the AltKey exists. In the failure handling of the validator set the message that you want to be displayed.
You can see an example of this here: http://www.gabrielsideras.com/2010/09/28/adf-unique-key-validation/
Gabriel -
How to parser a HTML page to get its variable and values?
Hi, everyone, here is my situation:
I need to parser a HTML page to get the variables and their associated values between <form>...</form> tag. for example, if you have a piece of HTML as below
<form>
<input type = "hidden" name = "para1" value = "value1">
<select name = "para2">
<option>value2</option>
</form>
the actual page is much complex than this. I want retrive pare1 = value1 and para2 = value2, I tried Jtidy but it doesn't reconginze select, could you recomend some good package this purpose? better with sample code.
Thanks a lot
KevinSee for example Request taglib from Coldtags suite:
http://www.servletsuite.com/jsp.htm -
Output of cmd in command prompt as key and vaule in properties file
hi,
i want to get the value of any command which i run using cmd in a properties file as a key and value rather then getting it in text file
for example - hostname>output.txt [not good], i want it to be like hostname>output.properties with a key and its value as output.
command - `hostname`
output - userpc
but i want the same output in a properties file like
xyzkey=userpc in sample.properties file.
it would be a great help.
thanks
sidI am sorry to say that it is not possible to understand what you are asking.
Please post a copy of your script with any error messages.
¯\_(ツ)_/¯ -
I want to search for a pattern string in the entire registry and need to delete all the keys and sub-keys that contain the pattern. How can I implement this in VB Script or C#? Appreciate if you can give some sample examples. Now every time, I am manually
searching for the pattern in registry and deleting one by one.
Thanks PrasadThere is no built in way to do this. You'll end up having to enumerate all keys and values in the entire registry and comparing each one for a pattern using Regex or similar. This is going to be really slow but there isn't much else you can do about
it (other than parallelize the enumeration). Also note that you won't have permissions to all keys for read and/or write access so you'll need to skip over those using exception handling.
Michael Taylor
http://blogs.msmvps.com/p3net -
Need help for displaying key and description in Dropdown (ABAP WEBDYNPRO)
Hi Experts,
I am using dropdown as a table field. For this dropdown I want to display the value as well as description.
In ALV table when we create a dropdown dynamically in table field, there is a method SET_KEY_VISIBLE in class CL_SALV_WD_UIE_DROPDOWN_BY_KEY.
But I think we cannot use similar method for normal dropdown field in table.
Is there any way we can display both value and description in dropdown value set ?
Please help.
Regards,
AnandHi,
I think there is no such option. You need to consider one variable type string and while populating the
valueset fill this variable by concatenating the value and description and assign it the key and value
pair of the valueset.
DATA:
lt_value_set_ctry type table of wdr_context_attr_value, " Country/Service Location
lv_str type string.
loop at lit_country into ls_country.
concatenate ls_country-value ls_country-text into lv_str separated by space.
ls_value_set-value = lv_str.
ls_value_set-text = lv_str.
append ls_value_set to lt_value_set_ctry.
clear ls_value_set.
endloop.
lr_node_info->set_attribute_value_set( name = 'COUNTRY'
value_set = lt_value_set_ctry ).
Consider this lit_country is a text table for countries.
Regards,
Lekha.
Maybe you are looking for
-
Routing internal users through UAG
We have published SharePoint on the UAG and want all internal users to access SharePoint through the UAG, as if they were connecting from outside our network. This is working. The problem is that we are trying to publish Office Web Apps for SharePoin
-
How to configure Oracle forms/reports 10g to Oracle Database 10g
Dear All, I have downloaded oracle Developer Suite 10g for microsoft Windows (CD1/CD2) from edelivery.oracle.com. I have also downloaded Oracle 10g xe edition from oracle.com. Both above software are on the same machine. Now, I have creaated new data
-
hi all, my servlet has provision for downloading a file, i have coded to display a dialog box at time of downloading file. my prob : when click on file to download browser displays save dialog box in IE 6 on one machine but the same servlet instead o
-
E-Mail processing error every 60 seconds, but still mails are handled?
Hi Guys, My "Operations Mnager" Event log file on the SCSM 2012 R2 Server is filling with the one error: Log Name: Operations Manager Source: SvcMgr Inbound Email Event ID: 27017 Task Category: None Level: Error Keywords:
-
ITunes will not save a video podcast
using iTunes 7.3, and after subscribing to a podcast, I am unable to save a video podcast. It goes through the down load process, but when complete it does not show up in the list of programs for a given podcast. The audio only podcast seem to be wor