I have few xml files like this
<?xml version = "1.0"?>
<note>
<to>Tim</to>
<from>Joe</from>
<head>About Job</head>
</note>
<?xml version = "1.0"?>
<note>
<to>Tim</to>
<from>Joe</from>
<head>How are u?</head>
</note>
<?xml version = "1.0"?>
<note>
<to>Marry</to>
<from>Pit</from>
<head>Welcome to home</head>
</note>
I parsing this files and store data into the text file like this
FROM:
Tim
Tim
Pit
TO:
Joe
Joe
Marry
HEAD:
About Job
How are u?
Welcome to home
I want the names are not repeated
How i can do it with hasMap, please help me! :)
If you only need a unique Collection of names, use a HashSet<String>. Only one instance would be stored for each unique name. HashMap would make sense if you want each unique name to serve as key. In that case you must decide what you want to store as the value for each name key.
From your question, it looks like you only need to store a collection of unique objects. Implementations of Set will help. You can use a HashSet of String objects:
Set uniqueNames = new HashSet<String>()
Set<String> from = new HashSet<String>();
You simply add new records with add method. Remember that set will not keep order in witch elements hav been inserted. But I suppose in your example you will sort names before printing, so it's ok.
If you want keep the iteration order use LinkedHashSet instead.
Read the text file and store the same into a HashSet like
Set names = new HashSet<String>();
names.put(nameString);
Above solution is case-sensitive - it means Tim and tim will be treated differently. Covert the name strings to lower case using "nameString".toLowerCase() before putting it into the HashSet if you are looking for case-insensitive behavior like
names.put(nameString.toLowerCase()); \\now Tim and tim will be treated equally
Hope this helps.
Related
I have a question about key-value pairs in a JSON array. Let's say I want to create a dynamic code that can be used across multiple responses where I want to pick out the first JSON array, how do I go about doing that? Currently, the code below looks for a JSON array known as 'test', but the issue here is that I can only use this code for an endpoint to spits out a JSON array that has the DTD 'test'.
What I was hoping is change the line of code below so that instead of 'test' it will be 0 or first or something like that.
httpResponse.getBody()
.getObject()
.getJSONArray("test")
.getJSONObject(0)
.get("value")
.toString();
Well, it's actually unusual to do that. Because the first item you put into a JSON object is not the first object you retrieve, JSON library puts it in an alphabetic order.
Either way, you can use the static method of JsonObject getNames() and get field names and then retrieve the first name.
EDIT:
Here is an example:
System.out.println(new JSONObject().put("second", "goes second").put("first","goes first").toString());
output:
{"first":"goes first","second":"goes second"}
And the static JSONObject.getNames():
for(String str:JSONObject.getNames(jsOb))
{
System.out.println("key="+str +", value="+jsOb.getString(str));
}
output:
key=first, value=goes first
key=second, value=goes second
I wish to achieve something like -
File.properties contains,
prop1, prop2 = valueX
prop3, prop4 = valueZ
where `props.getProperty("prop1");` should return `valueX`
I know one way is to write the same value again different keys but that makes my property file cluttered and does not provide an analytical view for the business purpose.
PS: If it is somehow possible then, please describe the case where the same key appears with different values.
I wish to achieve something like
File.properties contains,
prop1, prop2 = valueX
prop3, prop4 = valueZ
where props.getProperty("prop1"); should return valueX
The documentation for the .properties file format and the DTD for the XML properties format both provide only for mapping a single key at a time to an associated literal value. These simple formats do not support what you describe. The only alternative they afford is to give a value for each key separately, duplicating values as needed.
that makes my property file cluttered and does not provide an analytical view for the business purpose.
I guess that's in the eye of the beholder. Personally, I think your variation is just the flip side of the same coin. Either way, it is unclear whether keys bearing identical values do so incidentally or because it is important that their values be the same. And as far as writing such files for human consumption, I prefer the keys to be separate, as that makes them easier to find, and better affords grouping and sorting them.
If it is somehow possible then, please describe the case where the same key appears with different values.
Huh? Each key should have exactly one value. It is not documented what should happen if the same key appears more than once.
Perhaps you mean the same value being assigned to different keys, but I don't understand why that's in any question. Nevertheless, here:
prop1 = valueX
prop2 = valueX
prop3 = valueZ
prop4 = valueZ
Note that the = symbols can be replaced with : or just whitespace if you prefer. If you don't like that then you can define your own format, and write your own code for parsing an instance into a Properties object.
While sorting some data in a JTable I faced a problem when some German languages are present in the JTable.
I am giving a sample code that I tried out and the desired result that I require to work my application properly.
Code :
Vector<String> vec = new Vector<String>();
vec.add("ba~~~");
vec.add("ba~ab~~");
vec.add("ÇÊÕÝ");
vec.add("ÇÊÕÝ~ÂÉĒÐ~~");
System.out.println("Unsorted: "+vec);
Collections.sort(vec);
System.out.println("Sorted: "+vec);
Output :
Unsorted: [ba~~~, ba~ab~~, ÇÊÕÝ, ÇÊÕÝ~ÂÉĒÐ~~]
Sorted: [ba~ab~~, ba~~~, ÇÊÕÝ, ÇÊÕÝ~ÂÉĒÐ~~]
Output that I require:
Unsorted: [ba~~~, ba~ab~~, ÇÊÕÝ, ÇÊÕÝ~ÂÉĒÐ~~]
Sorted: [ba~ab~~, ba~~~, ÇÊÕÝ~ÂÉĒÐ~~, ÇÊÕÝ]
From the output I see that the string 'ba~ab~~' comes before 'ba~~~' which is correct lexicographically. But I could not understand why 'ÇÊÕÝ~ÂÉĒÐ~~' comes after 'ÇÊÕÝ'. My requirement is to get the desired output (as I mentioned above) for my application to work correctly.
Am I missing anything that I need to provide while comparing special languages.
Any useful help is highly appreciated.
Either you can use the built-in collators (Collator.getInstance(Locale.XXX))and implement compareTo, or if it is not a built-in collation, you will need to build your own using a RuleBasedCollator and then sort. For details on the rule-based collatorsee:
http://docs.oracle.com/javase/7/docs/api/java/text/RuleBasedCollator.html
Thanks a lot Sir...# Akber Choudhry...
Ultimately I found that ~ (tilt) character is the main culprit. To compare these set If I use the extended ASCII character 'ÿ' with maximum ASCII value 255 it solves the problem like a charm.
I found the extended ASCII chars from http://www.ascii-code.com/
I have a very specific requirment of comparing 2 xml strings in java. I have 2 xml strings. Original and modified. I need to compare the original xml string with the modified and find out what has been modified.
For example:
Original xml is
<Mycontacts>
<contact>
<firstName>Robert</firstName>
<PhoneNumber>9053428756</PhoneNumber>
<lastName>Bobbling</lastName>
<mobile>4168014523</mobile>
</contact>
<contact>
<firstName>Lily</firstName>
<PhoneNumber>9053428756</PhoneNumber>
<lastName>Bobbling</lastName>
<mobile>4168014523</mobile>
</contact>
</Mycontacts>
Modified xml:
<Mycontacts>
<contact>
<firstName>Robert</firstName>
<PhoneNumber>40454321333</PhoneNumber>
<lastName>Bobbling</lastName>
<mobile>4168014523</mobile>
</contact>
</Mycontacts>
As 1 contact is modified here and 1 id deleted I want to form 2 xml's trees. 1 is modify_xml and 1 is delete xml
modify xml:
<contact>
<firstName>Robert</firstName>
<PhoneNumber>40454321333</PhoneNumber>
<lastName>Bobbling</lastName>
<mobile>4168014523</mobile>
</contact>
delete xml:
<contact>
<name>Lily</name>
</contact>
How can this be done using java API's? Is parsing each node and creating a map for each contact entry a good option?
http://xmlunit.sourceforge.net/
I would parse the XML files to Java objects and compare those, assuming that the XML layout is not changing over time. You can use XStream or JAXB to do that.
Very difficult problem in the general case, for example if you want to detect that the element names have changed but the values have stayed the same, or if you want to detect that two elements are both still present but the order has been reversed. It's a lot easier if you know something about the structure of your data, and for example you are able to distinguish which values act as identifiers, so the problem reduces to finding an element in the other file with the same identifier and then asking which of its non-identifying properties have changed.
The essential point is that you need to say a lot more about the requirements before one can attempt a design.
I have 7 lines of data in a text file (shown below).
name: abcd
temp: 623.2
vel: 8
name: xyz
temp: 432
vel: 7.6
Using regex, I was able to read this data and I have been able to print it out. Now I need to store this data in some variable. I'm leaning towards storing this data in an array/ matrix. So physically, it would look something like this:
data = [abcd, 623.2, 8
xyz, 432, 7.6]
So in effect, 1st row contains the first 3 lines, the 2nd row contains lines from 5 to 7. My reason for choosing this type of variable for storage is that in the long run, calling out the data will be simpler - as in:
data[0][0] = abcd
data[1][1] = 432
I can't use the java matrix files from math.nist.gov because I'm not the root user and getting the IT dept to install stuff on my machine is proving to be a MAJOR waste of time. So I want to work with the resources I have - which is Eclipse and a java installation version 1.6.
I want to get this data and store it into a java array variable. What I wanted to know is: is choosing the array variable the right way to proceed? Or should I use a vector variable (altho, in my opinion, using a vector variable will complicate stuff)? or is there some other variable that will allow me to store data easily and call it out easily?
Btw, a little more details regarding my java installation - in case it helps in some way:
OpenJDK Runtime Environment (build 1.6.0-b09)
OpenJDK 64-bit Server VM (build 1.6.0-b09, mixed mode)
Thank you for your help
It seems to me that
name: abcd
temp: 623.2
vel: 8
is some sort of object, and you'd do well to store a list of these e.g. you would define an object
public class MyObject {
private String name;
private double temp;
private double vel;
// etc...
}
(perhaps - there may be more appropriate types), and store these in a list:
List<MyObject>
If you need to index them via their name attribute, then perhaps store a map (e.g.Map<String, MyObject>) where the key is the name of the object.
I'm suggesting creating an object for these since it's trivially easy to ask for obj.getName() etc. rather than remember or calculate array index offsets. Going forwards, you'll be able to add behaviour to these objects (e.g. you have a temp field - with an object you can retrieve that in centigrade/kelvin/fahrenheit etc.). Storing the raw data in arrays doesn't really allow you to leverage the functionality of a OO language.
(note re your installation woes - these classes are native to the Java JRE/JDK and don't require installations. They're fundamental to many programs in Java)
You can use an array, but rather than doing a two dimensional array, create a Data Class that holds the elements and then have an array of those elements.
For example:
public class MyData {
String name;
float temp;
int vel;
}
then you could define
MyData arr[];
You could also use a List() instead of an Array, depending on if you had sorting/searching type criteria. This approach gives you a lot more flexibility if you ever add an element or if you want to find duplicates or searching.
Wrap this information
name: xyz
temp: 432
vel: 7.6
in a class of it's own.
And use whichever implementation of a List<T> you prefer.
Provided that all keys in the key-value pair that you are reading are unique, why don't you store items in a java.util.Map?
Pattern pattern = Pattern.compile("(\\w+): (\\w+)");
try(BufferedReader reader = new BufferedReader(new FileReader("data.txt"))){
Map<String, String> items = new LinkedHashMap<>();
String line = null;
while( (line = reader.readLine()) != null) {
Matcher matcher = pattern.matcher(line);
while(matcher.find()){
items.put(matcher.group(1), matcher.group(2));
}
}
System.out.println(items);
}catch(IOException e) {
System.out.println(e.getMessage());
}
The map would then contain: {name=xyz, temp=432, vel=7}
And you could easily read a particular element like: items.get("name")
I think you can rely on java Collection framework.
You can use ArrayList instead of Arrays if there is a particular sequence in the data.
Moreover if you want to store data in key value pairs, then use Map.
Note: If you need sorted values, then use ArrayList with Comparator or Comparable Interface.
If you are using Map and you need unique and sorted values, then use TreeMap