I used Scanner to read through A.txt to generate A Hashmap,
also same method to read through B.txt to have B Hashmap.
These two hashmap have the "SOME" same key and would like to combine with each other.
If the key is are the same, print out "key, value1, value2".
Here is I have so far :
public static void main (String[] args) throws FileNotFoundException {
Scanner scanner1 = new Scanner(new File("score.txt"));
Map<String, String> tolerance = new HashMap<>();
Scanner scanner2 = new Scanner(new File("Count2.txt"));
Map<String, String> Pdegree = new HashMap<>();
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
String[] array = line.split("\t",2);
String Name = array[0];
String score = array[1];
tolerance.put(Name,score);
}
while (scanner2.hasNextLine()) {
String line2 = scanner2.nextLine();
String[] array2 = line2.split("\t",2);
String Name2 = array2[0];
String degree = array2[1];
Pdegree.put(Name2,degree);
}
for(Map.Entry<String, String> entry : tolerance.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
for(Map.Entry<String, String> entry2 : Pdegree.entrySet()) {
String key2 = entry2.getKey();
String value2 = entry2.getValue();
if(key==key2){
System.out.println(key2 + "\t" + value + "\t" + value2);
}
}
}
}
}
Neither results nor error messages would show.
My question is how to extract the same key with respective values from two maps. Thanks.
I found the answer by myself. It should be
if(key.equals(key2))
You may use map1.putAll(map2) to combine two maps;
Why not use Guava's multimap? I believe that if you use put all and it comes across two identical keys, it simply adds a second value to the key. Then you can print out all teh key value pairs. If it has identical key and identical value what it does is implementation dependent.
https://guava-libraries.googlecode.com/svn/tags/release03/javadoc/com/google/common/collect/Multimap.html#put(K, V)
Related
I need to split a sentence into two strings, the first string store as key and the second string store as value in HashMap.
For example:
String sent="4562=This is example";
This is my sentence, I split into two strings using the following line:
sent.split("=");
I want to store the first string (4562) as key, and the second string store as value in HashMap.
Can you please share your ideas or solution for problem?
You are stating your own answer:
HashMap<String, String> map = new HashMap<String, String>(); //initialize the hashmap
String s = "4562=This is example"; //initialize your string
String[] parts = s.split("="); //split it on the =
map.put(parts[0], parts[1]); //put it in the map as key, value
You can store in a hashmap like this:
String sent = "4562=This is example";
String[] split = sent.split("=");
HashMap<Integer, String> keysValues = new HashMap<Integer, String>();
keysValues.put(Integer.parseInt(split[0]), split[1]);
You can store Integer as key and String as value...or String, String either way will work depends on what you want.
the method split returns a String Array so store the result into an String array and call the hashmap.put(key,value) method
like this
String[] a = split.("=");
hasmap.put(a[0],a[1]);
note if you have several = in the string you will loose some of it in the value of the hashmap!
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<String, String>();
String s = "4562=This is example";
String[] parts = s.split("=");
if (parts.length == 2) {
myMap.put(parts[0], parts[1]);
}
System.out.println(myMap);
}
Output
{4562=This is example}
enter code here
I want to sort the map. I have string as key and integer as value.
Example:
key value
"1,3" 40
"1,5" 20
"2,5" 10
"2,10" 30
Output:
"2,5" 10
"1,5" 20
"2,10" 30
"1,3" 40
I tried the below code but it is not working. Can you please help me out.
treemap = treemap = new TreeMap<String, Integer>();
while((line = br.readLine()) !=null )
{
int sum=0;
sum = //something
String keys = xCordinate + "," + yCordinate; //getting it
treemap.put(keys, sum);
}
testMap(treemap );
}
public static void testMap(Map <String,Integer> map)
{
for(Integer value1 : map.values())
{
String keys = map.get(value1).toString(); //error in this line
System.out.println(keys + " " + value1);
}
}
Here, I get the perfect values in treemap..When I debug and see, the key value and count are perfect, but when i go in for loop, theere comes an error in second line.
StackTrace
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at java.lang.Integer.compareTo(Unknown Source)
at java.util.TreeMap.getEntry(Unknown Source)
at java.util.TreeMap.get(Unknown Source)
at TestJavaServer.testMap(TestJavaServer.java:75)
at TestJavaServer.readFromFile(TestJavaServer.java:68)
at TestJavaServer.main(TestJavaServer.java:22)
Asuming Java ,you could sort hashmap just like this :
public LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
List mapKeys = new ArrayList(passedMap.keySet());
List mapValues = new ArrayList(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap sortedMap = new LinkedHashMap();
Iterator valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
Object val = valueIt.next();
Iterator keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Object key = keyIt.next();
String comp1 = passedMap.get(key).toString();
String comp2 = val.toString();
if (comp1.equals(comp2)){
passedMap.remove(key);
mapKeys.remove(key);
sortedMap.put((String)key, (Double)val);
break;
}
}
}
return sortedMap;
}
Just a kick-off example , This way is more useful as it sorts the HashMap and keeps the duplicate values as well.
When you call map.get(something), that something must be of the same type as the map's key (String in your case), but you are passing in an Integer.
The code
public static void testMap(Map <String,Integer> map)
says that your map has keys of the type String, whereas here
String keys = map.get(value1).toString(); //error in this line
--
value1 is an integer, hence the exception.
I have a map whcih has the key value as long and value as String. The values of the map are obtained from the db and it is in the below format.
1: BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3,BusinessPartner.name4
2: BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3
6: ADDRESS.addressline1,ADDRESS.addressline2,ADDRESS.addressline3
where 1,2,6 are the keys.
I need to tokenize the strings that is for the key 1 the result should be
Businesspartner and the other values should be name1,name2,name3,name4.
I am doing this because i need to put these values into an another map as
Map(name1,name2,name3,name4)>
I can split the string but how to take Businesspartner as a common value for the other entities
Can anybody tell me how to do this
Thanks
would this work for your riquierment ?
public class Tokenize {
static Long keysFromDB[] = {1L, 2L, 6L};
static String stringsFromDB[] = {
"BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3,BusinessPartner.name4",
"BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3",
"ADDRESS.addressline1,ADDRESS.addressline2,ADDRESS.addressline3"};
#Test
public void tokenize() {
// use linked hashmap to preserve the order
Map<Long, Set<String>> tokenized = new LinkedHashMap<Long, Set<String>>();
int c = 0;
for(Long key : keysFromDB) {
// use linked hashset to preserve the order
Set<String> record = new LinkedHashSet<String>();
String splitedDBStrings[] = stringsFromDB[c++].split("\\.|,");
System.out.println("List: " + Arrays.asList(splitedDBStrings));
for(String s : splitedDBStrings) {
record.add(s);
}
System.out.println("Set: " + record);
tokenized.put(key, record);
}
System.out.println(tokenized);
}
}
run this
public static void main(String[] args){
Map<Long, String> dbmap = new HashMap<Long, String>();
dbmap.put((long) 1, "BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3,BusinessPartner.name4");
dbmap.put((long) 2, "BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3");
dbmap.put((long) 6, "ADDRESS.addressline1,ADDRESS.addressline2,ADDRESS.addressline3");
//Loop through the Map
Iterator<Entry<Long, String>> iterator = dbmap.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Long, String> entry = (Map.Entry<Long, String>) iterator.next();
//Split the string on comma ','
//result entries should be 'BusinessPartner.name1', 'BusinessPartner.name2' etc
String[] commaSplit = entry.getValue().split(",");
//loop through each entry
for(int x=0; x<commaSplit.length; x++){
//Split on Full Stop
//Result should be 'BusinessPartner', 'name2'
String[] dotSplit = commaSplit[x].split("\\.");
//print out common Value
System.out.println("Common Value is : " + dotSplit[0]);
//print out second value
System.out.println("Second Value is : " + dotSplit[1]);
System.out.println();
}
}
}
output is something like this
Common Value is : BusinessPartner
Second Value is : name1
Common Value is : BusinessPartner
Second Value is : name2
Common Value is : BusinessPartner
Second Value is : name3
Common Value is : BusinessPartner
Second Value is : name4
Common Value is : BusinessPartner
Second Value is : name1
Common Value is : BusinessPartner
Second Value is : name2
Common Value is : BusinessPartner
Second Value is : name3
Common Value is : ADDRESS
Second Value is : addressline1
Common Value is : ADDRESS
Second Value is : addressline2
Common Value is : ADDRESS
Second Value is : addressline3
Lets start from the beginning:
final Pattern pattern = Pattern.compile("[,\\s*]?([^.]+)\\.([^,]+)[,\\s*]?");
final Map<Long, String> myMap = getMapFromSomewhere();
for(final Map.Entry<Long, String> entry : myMap.entrySet()) {
final String myString = entry.getValue();
final Matcher matcher = pattern.matcher(myString);
final Map<String, List<String>> tokenised = new HashMap<String, List<String>>();
while (matcher.find()) {
final String key = matcher.group(1);
List<String> names = tokenised.get(key);
if(names == null) {
names = new LinkedList<String>();
tokenised.put(key, names)
}
names.add(matcher.group(2));
}
//do stuff with map.
}
The regex breaks down as follows:
[,\\s*]? optionally matches a comma followed by whitespace of unknown (or zero) length
([^.]+)\\. matches everything up to the next stop followed by a "."
([^,]+) takes everything upto the next comma in a match group
[,\\s*]? optionally matches a comma followed by whitespace of unknown (or zero) length
Test case:
public static void main(String[] args) {
final Pattern pattern = Pattern.compile("[,\\s*]?([^.]+)\\.([^,]+)[,\\s*]?");
final String myString = "BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3,BusinessPartner.name4";
final Matcher matcher = pattern.matcher(myString);
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
}
Output:
BusinessPartner
name1
BusinessPartner
name2
BusinessPartner
name3
BusinessPartner
name4
I have a HashMap with String as key and List as value.
Name of the HashMap is pageMap.
Say this pageMap has the following key and value:
key = order
value = [page1, page2, page3]
now I want to display in the following pattern:
order
page1
page2
page3
key2
value1
value2
value3
value4
Please tell me how do I do that?
import java.util.*;
import java.lang.*;
public class StringListMapExample {
public static String asTreeFormattedString(HashMap<String,List<String>> map) {
final StringBuilder builder = new StringBuilder();
for (String key : map.keySet()) {
builder.append(key + "\n");
for (String string : map.get(key)) {
builder.append("\t" + string + "\n");
}
}
return builder.toString();
}
public static void main(String[] args) {
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
map.put("order", Arrays.asList(new String[]{"page1", "page2", "page3"}));
System.out.println(asTreeFormattedString(map));
}
}
Actually the solution is quite straightforward.
hashmap.get(key).iterator();
is an iterator for the list of the given key.
Why did you not try to figure it out yourself?
Iterate using iterator through all keys of hashmap using keyset()
{
print key
Iterate through value list using iterator
{
print each value
}
}
public String formatDictionary(Map<String, List<String>> map){
String output = '';
for (String key : map.keySet()){
output = output + key + "\n";
for (String value: map.get(s)){
output = output + "\t" + value + "\n";
return output
Which is pretty similar to Jeppi's answer, but using string concatenation which is one of my favorite things about Java. I haven't run any benchmarks, but my guess is that his would be a little faster, but mine would have less overhead.
I have file which has String in the form key/value pair like people and count, example would be
"Reggy, 15"
"Jenny, 20"
"Reggy, 4"
"Jenny, 5"
and in the output I should have summed up all count values based on key so for our example output would be
"Reggy, 19"
"Jenny, 25"
Here is my approach:
Read each line and for each line get key and count using scanner and having , as delimiter
Now see if key is already present before if then just add currentValues to previousValues if not then take currentValue as value of HashMap.
Sample Implementation:
public static void main(final String[] argv) {
final File file = new File("C:\\Users\\rachel\\Desktop\\keyCount.txt");
try {
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
if (scanner.hasNext(".*,")) {
String key;
final String value;
key = scanner.next(".*,").trim();
if (!(scanner.hasNext())) {
// pick a better exception to throw
throw new Error("Missing value for key: " + key);
}
key = key.substring(0, key.length() - 1);
value = scanner.next();
System.out.println("key = " + key + " value = " + value);
}
}
} catch (final FileNotFoundException ex) {
ex.printStackTrace();
}
}
Part I am not clear about is how to divide key/value pair while reading them in and creating HashMap based on that.
Also is the approach am suggestion an optimal one or is there a way to enhance the performance more.
Since this is almost certainly a learning exercise, I'll stay away from writing code, letting you have all the fun.
Create a HashMap<String,Integer>. Every time that you see a key/value pair, check if the hash map has a value for the key (use 'containsKey(key)'). If it does, get that old value using get(key), add the new value, and store the result back using put(key, newValue). If the key is not there yet, add a new one - again, using put. Don't forget to make an int out if the String value (use Integer.valueOf(value) for that).
As far as optimizing goes, any optimization at this point would be premature: it does not even work! However, it's hard to get much faster than a single loop that you have, which is also rather straightforward.
Try this:
Map<String, Long> map = new HashMap<String, Long>();
while (scanner.hasNextLine()) {
if (scanner.hasNext(".*,")) {
....
if(map.containsKey(key))
map.put(key, map.get(key) + Long.valueOf(value));
else
map.put(key, Long.valueOf(value));
}
}
Simplest way I can think about splitting the values:
BufferedReader reader = new BufferedReader(new FileReader(file));
Map<String, Integer> mapping = new HashMap<String,Integer>();
String currentLine;
while ((currentLine = reader.readLine()) != null) {
String[] pair = currentLine.split(",");
if(pair.length != 2){ //could be less strict
throw new DataFormatException();
}
key = pair[0];
value = Integer.parseInt(pair[1]);
if(map.contains(key)){
value += map.get(key);
}
map.put(key,value);
}
It is most likely not the most efficient way in terms of performance, but is pretty straightforward. Scanner is usually used for parsing, but the parsing here doesn't look as complex, is just a split of strings.
For reading in, personally, I'd use:
Scanner.nextLine(), String.split(","), and Integer.valueOf(value)
Kind of late but clean solution with time complexity of O(n). This solution bypasses sort of arrays
public class Solution {
public static void main(String[] args) {
// Anagram
String str1 = "School master";
String str2 = "The classroom";
char strChar1[] = str1.replaceAll("[\\s]", "").toLowerCase().toCharArray();
char strChar2[] = str2.replaceAll("[\\s]", "").toLowerCase().toCharArray();
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (char c : strChar1) {
if(map.containsKey(c)){
int value=map.get(c)+1;
map.put(c, value);
}else{
map.put(c, 1);
}
}
for (char c : strChar2) {
if(map.containsKey(c)){
int value=map.get(c)-1;
map.put(c, value);
}else{
map.put(c, 1);
}
}
for (char c : map.keySet()) {
if (map.get(c) != 0) {
System.out.println("Not anagram");
}
}
System.out.println("Is anagram");
}
}
public Map<String, Integer> mergeMaps(#NonNull final Map<String, Integer> mapOne,
#NonNull final Map<String, Integer> mapTwo) {
return Stream.of(mapOne.entrySet(), mapTwo.entrySet())
.flatMap(Collection::stream)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Integer::sum));
}