Obtaining keys from java.util.TreeMap values (help)
I don't know how i can obtain the keys from the values in the java.util.TreeMap. I can iterate through the key-values collection, but i don't know how i can specify a value to obtain a key.
That's because Maps map keys to values, not the other way around. If you want to see what key(s) (there may be none or many) map to a particular value, you must examine all values in the Map. You could instead have two Maps, one to map keys to values and the other to map values to keys.
Similar Messages
-
Hi all,
How to change a date value from "java.util.Date" to "java.sql.Date"?
I m still confusing what's the difference between them.....
thanks
Regards,
KinThanks
but my sql statement can only accept the format (yyyy-MM-dd)
such as "select * from xx where somedate = '2004-12-31'
but when i show it to screen, i want to show it as dd-MM-yyyy
I m using the following to change the jave.util.Date to str and vice versa. But it cannot shows the dd-MM-yyyy. I tried to change the format from yyyy-MM-dd to dd-MM-yyyy, it shows the wrong date in my application.
public String date2str(java.util.Date thisdate) {
if (thisdate != null) {
java.sql.Date thissDate = new java.sql.Date(thisdate.getTime());
return date2str(thissDate);
} else {
return "";
public String date2str(java.sql.Date thisdate) {
if (thisdate != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(thisdate);
} else {
return "";
public java.util.Date str2date(String thisdate) {
String dateFormat = "yyyy-MM-dd"; // = 1998-12-31
java.util.Date returndate = null;
if (thisdate != null) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
try {
returndate = dateFormatter.parse(thisdate);
} catch (ParseException pe) {
System.out.println (pe.getMessage());
return returndate;
} -
Is there a Java utility class to help with data management in a desktop UI?
Is there a Java utility class to help with data management in a desktop UI?
I am writing a UI to configure a network device that will be connected to the serial port of the computer while it is being configured. There is no web server or database for my application. The UI has a large number of fields (50+) spread across 16 tabs. I will write the UI in Java FX. It should run inside the browser when launched, and issue commands to the network device through the serial port. A UI has several input fields spread across tabs and one single Submit button. If a field is edited, and the submit button clicked, it issues a command and sends the new datum to the device, retrieves current value and any errors. so if input field has bad data, it is indicated for example, the field has a red border.
Is there a standard design pattern or Java utility class to accomplish the frequently encountered, 'generic' parts of this scenario? lazy loading, submitting only what fields changed, displaying what fields have errors etc. (I dont want to reinvent the wheel if it is already there). Otherwise I can write such a class and share it back here if it is useful.
someone recommended JGoodies Bindings for Swing - will this work well and in FX?Many thanks for the reply.
In the servlet create an Arraylist and in th efor
loop put the insances of the csqabean in this
ArrayList. Exit the for loop and then add the
ArrayList as an attribute to the session.I am making the use of Vector and did the same thing as u mentioned.I am using scriplets...
>
In the jsp retrieve the array list from the session
and in a for loop step through the ArrayList
retrieving each CourseSectionQABean and displaying.
You can do this in a scriptlet but should also check
out the jstl tags.I am able to remove this problem.Thanks again for the suggestion.
AS -
Using ExecutorService class from java.util.concurrent package
Dear java programmers,
I have a question regarding the ExecutorService class from java.util.concurrent package.
I want to parse hundreds of files and for this purpose I'm implementing a thread pool. The way I use the ExecutorService class is summarized below:
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++){
System.out.println("Parsing file No "+i);
executor.submit(new Dock(i));
executor.shutdown();
try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
ex.printStackTrace();
executor.shutdownNow();However, the code snippet above creates all the 1000 threads (Dock objects) at once and loads them to the executor, and thus I'm worrying about memory leak. I haven't tested it on 1000 files yet but just on 50 small ones, and even if the program prints out "Parsing file No "+i 50 times at once, it executes normally the threads in the background.
I guess the write way would be to keep the number of active/idle threads in the executor constant (lets say 20 if the thread pool's size is 10) and submit a new one whenever a thread has been finished or terminated. But for this to happen the program should be notified someway whenever a thread is done. Can anybody help me do that?
thanks in advance,
TomOk I found a feasible solution myself although I'm not sure if this is the optimum.
Here's what I did:
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<String> future0, future1, future2, future3, future4, future5, future6, future7, future8, future9;
Future[] futureArray = {future0 = null, future1 = null, future2 = null, future3 = null, future4 = null, future5 = null,
future6 = null, future7 = null, future8 = null, future9 = null};
for (int i = 0; i < 10; i++){
futureArray[i] = executor.submit(new Dock(i));
}I created the ExecutorService object which encapsulates the thread pool and then created 10 Future objects (java.util.concurrent.Future) and added them into an Array.
For java.util.concurrent.Future and Callable Interface usage refer to:
[http://www.swingwiki.org/best:use_worker_thread_for_long_operations]
[http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter10/concurrencyTools.html]
I used a Future[] Array to make the code neater. So after that I submitted -and in this way filled up- the first 10 threads to the thread pool.
int i = 9;
while (i < 1000){
for (int j = 0; j < 10; j++){
if (futureArray[j].isDone() && i < 999){
try{
i++;
futureArray[j] = executor.submit(new Dock(i));
} catch (ExecutionException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
try {
Thread.sleep(100); // wait a while
} catch(InterruptedException iex) { /* ignore */ }
executor.shutdown();
try {
executor.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
ex.printStackTrace();
executor.shutdownNow();
}Each of the future[0-9] objects represents a thread in the thread pool. So essentially I'm check which of these 10 threads has been finished (using the java.util.concurrent.Future.isDone() method) and if yes I replenish that empty future[0-9] object with a new one. -
Cannot convert from java.util.Date to java.sql.Date
In the below code am trying to get the current date and 60 days prior date:
Date todayDate;
Date Sixtydaysprior;
String DATE_FORMAT = "MM/dd/yy";
DateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Calendar cal = Calendar.getInstance();
todayDate = sdf.parse(sdf.format(cal.getTime()));
cal.add(Calendar.DATE, -60);
Sixtydaysprior = sdf.parse(sdf.format(cal.getTime()));I have imported following files:
<%@page
import="java.util.Calendar,
java.text.SimpleDateFormat,
java.text.ParseException,
java.util.*"
%>Shows up following error msg:
Type mismatch: cannot convert from java.util.Date to java.sql.Date
Thanks.
Edited by: MiltonDetroja on May 22, 2009 11:03 AMShows up following error msg:
Type mismatch: cannot convert from java.util.Date to java.sql.Date
I don't think this exception is thrown from the portion of code you have shown. As clearly specified in exception message, you cannot cast an instance of java.util.Date to java.sql.Date. you will need to do something like this
java.util.Date today = new java.util.Date();
long t = today.getTime();
java.sql.Date dt = new java.sql.Date(t); -
Calling html from java with some values
Hello friends,
I can call a HTML file from java.I want to pass some values from java class file to that html file.Anybody help me how to pass parameters?
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler http://localhost:8080/jcoDemo/dp.html");
is one i am using for calling html file
thanksJust add GET query parameters to the URL.
Besides, if you were using Java 1.6 or newer, then rather use [Desktop#browse()|http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#browse(java.net.URI)] instead of Runtime#exec(). It is crossplatform while your runtime approach works in Mircosoft Windows systems only. -
I need to retrieve an Object[] of all keys in java.util.Hashtable
public abstract class ArrayFunctionality {
* Construct {@link java.lang.Object} array of keys from {@link java.util.Hashtable}
* @param h {@link java.util.Hashtable}
* @return array {@link java.lang.String}
* @throws java.lang.IndexOutOfBoundsException Exception thrown if initial {@link java.lang.Object} array paramater cannot be indexed
public static Object[] arrayKeys(Hashtable<Object, Object> h) throws IndexOutOfBoundsException {
Vector<Object> v = new Vector<Object>();
Enumeration keys = h.keys();
while (keys.hasMoreElements()) v.add(keys.nextElement());
return v.toArray();
// HOWEVER, this occurs with Hashtable<String, String> attrs:
if (hasSetHashtable) String[] keyArray = ArrayFunctionality.arrayKeys(attrs);
// DOES NOT COMPILE: ".class expected - not a statement"I am not understanding why this is occurring, please advise, I'm lost on this one.
Thanx
PhilI still don't understand what you mean but it now
works..
I am sorry I just don't understand the difference
between
if (hasSetHashtable) {
String[] keyArray;
keyArray = ArrayFunctionality.arrayKeys(attrs);
}AND
if (hasSetHashtable) {
String[] keyArray =
ArrayFunctionality.arrayKeys(attrs);PhilThere is no difference between those two you posted. The difference is between
String[] keyArray;
if (...) {
keyArray = ArrayFunctionality.arrayKeys(attrs);
}and
if (...) {
String[] keyArray;
keyArray = ArrayFunctionality.arrayKeys(attrs);
}In the first, the keyArray will exist outside of the scope of the if statement. In the second, the keyArray will no longer exist once you leave the if statement. Which is the same thing jbish said. -
Java.util.vector value to String
Hi
I am trying to use some API calls for securecomputing. One of the value when i print using API, i get the result as
java.util.Vector$1@93d6bc
How do i convert this value into readable string format.
Thanks for any help
JosephEven after adding toString() it still returns the
same value.
System.out.println("Role " +
(user.getValue(User.IDS_ROLE)).toString());
Returns "Role java.util.Vector$1@93d6bc"
User.IDS_ROLE is an int
Thanks for the repliesWe didn't mean for you to explicitly call toString(), we meant for you to implement it. What kind of class does user.getValue(int) return? Surely it's not a java.util.Vector, but something else - what it is returning looks confusing (java.util.Vector$1...) -
Unable to capture messages from java.util.logging
I have a class called (Caller.java) which invokes a method called foo from another java class(Util.java) using reflection API.Now this method foo logs messages using Java's logger.My requirement is to call foo for 3 times from Caller and capture/redirect the log messages into 3 log files.
But only the first log file is capturing the log messages(from logger) and other two are not ?
Plz suggest if I am doing somethin wrong here ?
Caller.java
package project2;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.lang.reflect.Method;
public class Caller {
public Caller() {
public static void main(String[] args) throws Exception {
Caller caller = new Caller();
for (int i = 0 ;i<3 ;i++ ) {
caller.createLogStream(i);
System.setOut(caller.getPs());
System.setErr(caller.getPs());
/*****************Invoking Util.java*****************************/
Class clas = Class.forName("project2.Util");
Method m = clas.getMethod("foo",null);
Object obj =clas.newInstance();
m.invoke(obj,null);
public void createLogStream(int i) throws FileNotFoundException {
ps = new PrintStream(new File(System.getenv("HOME")+File.separator+"MyLog"+i+".log"));
public void closeLogStream(){
ps.close();
ps = null;
private PrintStream ps = null;
public PrintStream getPs() {
return ps;
} Util.java
package project2;
import java.util.logging.Logger;
public class Util {
Logger logger = null;
public Util() {
logger = Logger.getLogger(this.getClass().getName());
public void foo(){
System.out.println("Hello out stream");
System.err.println("Hello error stream");
logger.info("This is an information");
logger.warning("This is a warning message");
logger.severe("This is fatal!! ");
}First Log file MyLog0.log:
Hello out stream
Hello error stream
Feb 16, 2009 7:55:55 PM project2.Util foo
INFO: This is an information
Feb 16, 2009 7:55:55 PM project2.Util foo
WARNING: This is a warning message
Feb 16, 2009 7:55:55 PM project2.Util foo
SEVERE: This is fatal!!
Feb 16, 2009 7:55:55 PM project2.Util foo
INFO: This is an information
Feb 16, 2009 7:55:55 PM project2.Util foo
WARNING: This is a warning message
Feb 16, 2009 7:55:55 PM project2.Util foo
SEVERE: This is fatal!!
Feb 16, 2009 7:55:55 PM project2.Util foo
INFO: This is an information
Feb 16, 2009 7:55:55 PM project2.Util foo
WARNING: This is a warning message
Feb 16, 2009 7:55:55 PM project2.Util foo
SEVERE: This is fatal!! Other 2 log files have only this much
Hello out stream
Hello error streamA stale Connection Factory or Connection Handle may be used in SOA 11g
Regards,
Anuj -
How To Add Days into a Date from java.util.Date class
I have a problem when i wants to add 2 or days into a
date object geting by java.util.Date class. so please help me resolve this issue?
for e.g i have a date object having 30/06/2001,
by adding 2 days i want 02/07/2001 date object ?
Code
public class test2
public static void main(String args[])
java.util.Date postDate = new java.util.Date();
myNewDate = postDate /* ?*/;
Here i want to add 2 date into postDateUse Calendar...
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY, 2); // I'm not sure about that "DAY" -
Getting no output from java.util.logging.FileHandler
I am new to Java as is the company I work for, but we have just landed a contract that specifies J2EE as the platform, so here we are. :-) Please bear with me.
I have been charged with determining our logging architecture and it looks like what is available in java.util.logging will do well (though we may use log4j). However, at this point I am just trying to get anything to work and not having much luck.
We are using JSF on the front end and I have created a very simple JSF page to test logging. The relevant code is below and I hope will be self explanatory: This code is not meant to be efficient or anything. It is just a proof of concept.
public String button1_action() {
// User event code here...
try {
Logger l = java.util.logging.Logger.getLogger(Page1.class.getName());
l.entering(Page1.class.getName(), "button1_action");
l.info(this.textField1.getValue().toString());
l.exiting(Page1.class.getName(), "button1_action");
java.util.logging.Handler h = l.getHandlers()[0];
h.flush();
catch(Exception ex) {
//I have tested this and we aren?t catching any errors.
System.err.println(ex);
return "";
}My logger.properties files looks like this:
handlers= java.util.logging.FileHandler
.level= FINEST
java.util.logging.FileHandler.pattern = c:/sun/logs/test-%u.log
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatterI have developed and tested this in Sun Studio Creator 2004Q2 What is happening is that I am getting three log files in c:/sun/logs
test-0.log, test-1.log and test-2.log. The first two contain output from various sun components. (sun.rmi.transport for example). The third log remains empty. (zero length)
I have also deployed the test app to a tomcat 5.0.28 server and get similar results. The only difference is I get only one two log files and the second one remains empty.
Any assistance or suggestions as to what direction I should be taking would be appreciated.
--KenDo not use default logger as getLoggers[0] , but use your java.util.Logger.FileHandler and add filehandler object to log your fButtonActions and you do not need to mess with logger.properties too.
-
Java.util.TreeMap
hi,
We have a list of key,value pairs of state codes and state names implemented using TreeMap. The list is sort based on the key value but in the display when getting the values some of them are out of order.
say the key, value pair - sorted on values (as desired to be seen in listbox)
NE,Nebraska
NV,Nevada
NH,New Hampshire
NJ,New Jersey
NM,New Mexico
NY,New York
NC,North Carolina
ND,North Dakota
but the TreeMap sorts on the key and while getting the values on the UI, it is
North Carolina
North Dakota
Nebraska
New Hampshire
New Jersey
New Mexico
Nevada
New York
Is there a way to get the treeMap sorted on the values ?Don't use strings. Use an object that contains both the abbreviation and the full name of the state. Have the toString() method return the full name... never mind, like this:public class USState implements Comparable {
private String code;
private String name;
public USState(String pCode, String pName) {
code = pCode;
name = pName;
public String toString() {
return name;
public String getStateCode() {
return code;
public int compareTo(Object other) {
that = (USState) other;
return this.name.compareTo(that.name);
public boolean equals(Object other) {
that = (USState) other;
return this.name.equals(that.name);
public int hashCode() {
return name.hashCode();
}Then you can use "NC" as the key in your Map and new USState("NC", "North Carolina") as the value. It doesn't need to be a TreeMap because you don't need the list sorted by state code. You can sort the values set of your Map and you'll have the states in alphabetic order by name along with their abbreviations. -
Excel from JAVA or C++ -- Urgent -- help
Hi
I know it might not be possible, but i want to use couple of Financial Functions which excel provides within itself.
Is there anyway i can use them from my JAVA or C++ code ?
In short, would it be possible to call excel functions from JAVA or C++ code
TIA
VikramActually you can... In quite a few different ways. You can access any COM or OLE object in windows from within java by using the Java/COm bridge, or purchasing shrink wrapped products... The links are below:
These people provide some very cool solutions for java. This link is specifically for excel.
http://www.intrinsyc.com/pdfs/java-excel_bridge.pdf
Some Resources for Java/COM...
http://users.rcn.com/danadler/javacom/ -
Obtaining keys from old KMS server for permanent use?
We have a client who bought a series of PCs that had previously been on loan from a software company. They discovered about 6 months after the fact that their copies of Office 2010 and Windows 7 on those machines were coming up as deactivated.
My question is: Can you obtain a permanent key for Office/Windows for a KMS activation after the device has been removed from the network with the KMS server?fukawi2 wrote:
rsty wrote:How much power does a server use... when it's not being "used" And what about power configurations, for people who have the same deal as me. Because I wont be using it 24/7.
I have a couple of these exact units for home... They are loud and expensive. I don't have exact figures, but I can't afford to run them. I bought a rack-case and built a custom "server" instead. The DL380's are now at work instead (where I don't pay the electricity bill )
Thanks. I wonder how it would be with green SATA drives and some power config tweaks. For now, I'll stick with my backup drive in my desk drawer and rsync for my laptop. Thanks all. -
Hi... I am writing a java program that fetches a table from database and creates a Crystal Report from that table(ResultSet object)... Optionally exporting the report as a pdf also... This will be a console application since it is my first program using crystal reports.... Any one can help me with this...?
Hi Karthik,
you could have a look over these developer guides below for understanding of Java sdk :-
[http://www.sdn.sap.com/irj/boc/sdklibrary|http://www.sdn.sap.com/irj/boc/sdklibrary]
you could also find below sample codes for creating reports using Java sdk (RAS sdk) :-
[http://www.sdn.sap.com/irj/boc/samples|http://www.sdn.sap.com/irj/boc/samples]
let me know if you need any help,
Regards,
Rameez.
Maybe you are looking for
-
Applescript say app names during Cmd + Tab
I'm writing a script for a speakable item that will let me switch applications without having to touch the computer, by invoking the Cmd+Tab functionality. So far, I have the following: tell application "System Events" key down command key
-
Depcapricate?????
I downloaded a sample java file (SmallSample.java) When I try to compile the file like javac SmallSample.java I get the following compile error. "SmallSample..class uses or overrides a deprecated API" What does it means???? What is Deprecate??? Any h
-
Cannot create a dump file for a process
Hi fellows, I have a problem creating a dump file for an application. The application consists of C++ and C# dlls. It runs in Windows 7 64bit environment. I constantly receive the following error: ERROR_PARTIAL_COPY: Only part of a ReadProcessMemory
-
I must be missing the obvious over here..from what I understood of HashSet's/equals and hashCode, the program below should not add the Person object twice. Please suggest whats wrong... import java.util.*; public class TestHashSet2 { Set set = null;
-
I have a 3 part lease form, how can I convert it into an Adobe/PDF File with fields for editable text?