As part of my HOMEWORK, I am trying to read a file made up of car models and output the total of each to the console.
I have achieved this so far by using a Map with the model name as the key and the counter as the value.
Although, now I want to only output models that are added to a Set.
So, if Fiat was in the file, it wouldnt be used as it is not in the allowable Set.
Hopefully that makes sense and help is appreciated.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
public class Test
{
public static void main(String[] args) throws FileNotFoundException
{
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
Set<String> fruit = new TreeSet<String>();
fruit.add("BMW");
fruit.add("Mercedes");
fruit.add("Ford");
fruit.add("Nissan");
fruit.add("Tesla");
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
while (in.hasNext())
{
String word = in.next();
if (map.containsKey(word))
{
int count = map.get(word) + 1;
map.put(word, count);
}
else
{
map.put(word, 1);
}
}
in.close();
for (Map.Entry<String, Integer> entry : map.entrySet())
{
System.out.println(entry);
}
}
}
You could just iterate through your set and then invoke the map's "get" method.
e.g.
for ( String car : fruit ) {
Integer value = map.get( car );
if ( value != null ) {
System.out.println( value );
}
}
If the result is not null then print it to the console, otherwise, look for the next one.
try this,
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
Set<String> fruit = new TreeSet<String>();
fruit.add("BMW");
fruit.add("Mercedes");
fruit.add("Ford");
fruit.add("Nissan");
fruit.add("Tesla");
map.put("BMW", 2);
map.put("Ford", 2);
map.put("SomeOther", 2);
System.out.println(map);
map.keySet().retainAll(fruit);
System.out.println(map);
System.out.println(map.keySet());
Related
How can I clone contents of Stringbuilder based on number of records and append record to each row of cloned contents. I'm trying to write data to CSV in way each rows have duplicate columns values repeated by times size of records.
Sample Output CSV should look like.
CN1| CN2| CN3
1 b c
1 d f
2 g h
Here's sample Java Code I'm using
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CSVWrite {
public static Map<String, List<Records>> getData() {
Map<String, List<Records>> fields = new HashMap<>();
List<Records> records_1 = new ArrayList<>();
Records sample_1 = new Records();
sample_1.setName("b");
sample_1.setId("c");
Records sample_2 = new Records();
sample_2.setName("d");
sample_2.setId("f");
records_1.add(sample_1);
records_1.add(sample_2);
List<Records> records_2 = new ArrayList<>();
Records sample_3 = new Records();
sample_1.setName("g");
sample_1.setId("h");
records_2.add(sample_3);
fields.put("1", records_1);
fields.put("2", records_2);
return fields;
}
public static void main(String args[]) {
CSVWrite write = new CSVWrite();
String csvString = write.getCsvString();
String expectedString = "1,b,c\n" + "1,d,f\n" + "2,g,h";
System.out.println(csvString.equals(expectedString));
}
public String getCsvString() {
Map<String, List<Records>> fields = CSVWrite.getData();
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, List<Records>> entry : fields.entrySet()) {
sb.append(entry.getKey());
List<Records> records = entry.getValue();
for (int i = 0; i < records.size(); i++) {
// how to clone contents of sb repeated times based on records size and append
// record items to all.
}
}
return sb.toString();
}
}
First, there is an error I think, this code look weird. The var sample_3 is built but not correctly populated:
Records sample_3 = new Records();
sample_1.setName("g");
sample_1.setId("h");
It should be:
Records sample_3 = new Records();
sample_3.setName("g");
sample_3.setId("h");
Finally, there is no need to clone anything to achieve the desired result, simply rewrite getCsvString() like this:
public String getCsvString() {
Map<String, List<Records>> fields = CSVWrite.getData();
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, List<Records>> entry : fields.entrySet()) {
List<Records> records = entry.getValue();
for (Records record : records) {
sb.append(entry.getKey());
sb.append(",").append(record.getName());
sb.append(",").append(record.getId());
sb.append("\n");
}
}
return sb.toString();
}
Those 2 corrections will generate output:
1,b,c
1,d,f
2,g,h
I have a query string like
"1_timestamp=201612312&1_user=123&2_timestamp=20145333&2_user=5432";
But I want to make them in array like below.
array(
0 => (
timestamp = 201612312,
user = 123,
),
1 => (
timestamp = 201612312,
user = 123,
),
);
I'm sorry to show you php type of array though I'm new to java.
How do I make it something like that?
Thank you
This is the closest structure to what you are doing in php, and if your data has more fields it can be easily added to the Data class:
import java.util.ArrayList;
import java.util.List;
class Data {
int timestamp;
int user;
Data(int ts, int user) {
this.timestamp = ts;
this.user = user;
}
}
public class Test {
public static void main(String[] args) {
List<Data> data = new ArrayList<Data>();
Data d1 = new Data(201612312, 123);
Data d2 = new Data(201612312, 123);
data.add(d1);
data.add(d2);
System.out.println(data.get(1).user);
}
}
You can do it without writing a class. You can use it like this.
Map<String, String> map1 = new HashMap<String, String>();
map1.put("1_timestamp", "201612312");
map1.put("1_user", "123");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("2_timestamp", "20145333");
map2.put("2_user", "5432");
List<Map<String,String> mapList = new ArrayList<Map<String, String>>();
mapList.add(map1);
mapList.add(map2);
for (Map<String, String> map : list) {
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
I have a nested HashMap (outer_map), which has another HashMap inside of it as a value (inner_map), such implemented as
Map<String, HashMap<String, String>> outer_map = new HashMap<String, HashMap<String, String>>();
Map<String, String> inner_map = new HashMap<String, String>();
The figure below illustrates the whole structures of the maps:
To make the long story short, I need to compare and search values inside the outer_map's vlaue (inner_map) by String Array items, and then produce another String Array to add matched items.
If the String Array has there elements which are the same as one of the inner_map's random (for example; value2, value1, and value7) values, how can I search and compare these items to add to another String Array?
The latest code snippet I tried and I couldn't succeed:
if( !( theStringArray.equals("") ) )
{
while( outer_map.keySet().iterator().hasNext() )
{
for( int i=0; i <= theStringArray.length; i++)
{
// outer_map keys are order as 1,2,3,..,8
theStringArray[i] = outer_map.get(String.valueOf(i+1)).get("key1");
...
}
}
}
EDIT: Map generating function
private void parse(String in) throws IOException
{
reader = new JsonReader(new StringReader(in));
...
int nodeCounter = 1;
while(reader.hasNext())
{
...
String nameAsKey1 = "blabla"; // value1
inner_map.put("name", nameAsKey1);
String surnameAsKey2 = "blabla"; // value2
inner_map.put("surname", surnameAsKey2);
...
outer_map.put(String.valueOf(nodeCounter), (HashMap<String, String>) inner_map);
inner_map = new HashMap<String, String>();
nodeCounter++;
}
}
EDIT: I don't know how I can explain the issue more clearly, but may be this will help to understand about it: Map structure
I assume you have an array of String and a Map of map. Now you want to search the value fields of inner map against the array of String and if make a new string array with matching values.
If that is the case the below program will help you..
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class InnerMapSearch {
public static void main(String[] args) {
Map<String, HashMap<String, String>> outer_map = new HashMap<String, HashMap<String, String>>();
Map<String, String> inner_map = new HashMap<String, String>();
String[] searchParams = {"blabla1", "blabla3", "blabla20"};
//Populating the map
int reader = 1;
while (reader < 10) {
String nameAsKey1 = "blabla" + reader; // value1
inner_map.put("name", nameAsKey1);
String surnameAsKey2 = "blabla" + reader; // value2
inner_map.put("surname", surnameAsKey2);
outer_map.put(String.valueOf(reader), (HashMap<String, String>) inner_map);
inner_map = new HashMap<String, String>();
reader++;
}
//Searching
Set<String> searchResults = new HashSet<String>(); // Using set to avoid duplicate
// Iterate over the outer map
for(String key : outer_map.keySet()){
// Iterate through each inner_map value of outer map
for(Entry<String, String> innerEntry : outer_map.get(key).entrySet()){
// Iterate through the list of search params and see if its present in inner_hashmap
for(String searchParam : searchParams){
if(searchParam.equals(innerEntry.getValue())){
// The search parameter is in inner map so adding to result.
searchResults.add(searchParam);
}
}
}
}
// Converting the list to an array.
String[] searchResultsArray = searchResults.toArray(new String[searchResults.size()]);
}
}
String format is (not json format):
a="0PN5J17HBGZHT7JJ3X82", b="frJIUN8DYpKDtOLCwo/yzg="
I want convert this string to a HashMap:
key a with value 0PN5J17HBGZHT7JJ3X82
key b with value frJIUN8DYpKDtOLCwo/yzg=
Is there a convenient way? Thanks
What I've tried:
Map<String, String> map = new HashMap<String, String>();
String s = "a=\"00PN5J17HBGZHT7JJ3X82\",b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
String []tmp = StringUtils.split(s,',');
for (String v : tmp) {
String[] t = StringUtils.split(v,'=');
map.put(t[0], t[1]);
}
I get this result:
key a with value "0PN5J17HBGZHT7JJ3X82"
key b with value "frJIUN8DYpKDtOLCwo/yzg
for key a, the start and end double quotation marks(") is unwanted; for key b, the start double quotation marks(") is unwanted and the last equals sign(=) is missing.
Sorry for my poor english.
Probably you don't care that it's a HashMap, just a Map, so this will do it, since Properties implements Map:
import java.io.StringReader;
import java.util.*;
public class Strings {
public static void main(String[] args) throws Exception {
String input = "a=\"0PN5J17HBGZHT7JJ3X82\", b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
String propertiesFormat = input.replaceAll(",", "\n");
Properties properties = new Properties();
properties.load(new StringReader(propertiesFormat));
System.out.println(properties);
}
}
Output:
{b="frJIUN8DYpKDtOLCwo/yzg=", a="0PN5J17HBGZHT7JJ3X82"}
If you absolutely need a HashMap, you can construct one with the Properties object as input: new HashMap(properties).
Added few changes in Ryan's code
public static void main(String[] args) throws Exception {
String input = "a=\"0PN5J17HBGZHT7JJ3X82\", b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
input=input.replaceAll("\"", "");
String propertiesFormat = input.replaceAll(",", "\n");
Properties properties = new Properties();
properties.load(new StringReader(propertiesFormat));
Set<Entry<Object, Object>> entrySet = properties.entrySet();
HashMap<String,String > map = new HashMap<String, String>();
for (Iterator<Entry<Object, Object>> it = entrySet.iterator(); it.hasNext();) {
Entry<Object,Object> entry = it.next();
map.put((String)entry.getKey(), (String)entry.getValue());
}
System.out.println(map);
}
Split the String on the Basis of commas (",") and then with with ("=")
String s = "Comma Separated String";
HashMap<String, String> map = new HashMap<String, String>();
String[] arr = s.split(",");
String[] arStr = arr.split("=");
map.put(arr[0], arr[1]);
You can also use the regex as below.
Map<String,String> data = new HashMap<String,String>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
for ( int i=0; i+2 <= split.length; i+=2 ){
data.put( split[i], split[i+1] );
}
return data;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
public class shift {
#SuppressWarnings("unchecked")
public static void main(String args[])
{
String speech = "Sentence:NounPhrase VerbPhrase:NounPhrase :Art Noun:VerbPhrase : Verb | Adverb Verb: Art : the | a : Verb :jumps | sings |: Noun:dog | cat | ";
HashMap<String, String> hashmap = new HashMap<String, String>();
String a;
StringTokenizer st = new StringTokenizer(speech,":");
while (st.hasMoreTokens()) {
String key=st.nextToken().trim();
String value=st.nextToken().trim();
StringTokenizer st1 = new StringTokenizer(value,"|");
while (st1.hasMoreTokens()) {
a=st1.nextToken().trim();
hashmap.put(key, a);
}
}
Set set = hashmap.entrySet();
Iterator ia = set.iterator();
while(ia.hasNext()) {
Map.Entry me = (Map.Entry)ia.next();
System.out.println(me.getKey()+"->"+me.getValue());
}
}
}
the output is
Noun->cat
NounPhrase->Art Noun
Art->a
Sentence->NounPhrase VerbPhrase
Verb->sings
VerbPhrase->Adverb Verb
this code is missing some values to return such as the the jumps etc are not show
Not sure I get your question fully, but keep in mind that a HashMap can only store one value per key.
If you want to store multiple verbs for the key "Verb", then you would have to declare the map using something like:
HashMap<String, Set<String>> hashmap = new HashMap<String, Set<String>>();
and store the words mapped to by "Verb" in a set.
Here is a brushed up (working) version of the code:
import java.util.*;
public class Shift {
public static void main(String args[]) {
String speech = "Sentence:NounPhrase VerbPhrase:NounPhrase :Art " +
"Noun:VerbPhrase : Verb | Adverb Verb: Art : the | " +
"a : Verb :jumps | sings |: Noun:dog | cat | ";
Map<String, Set<String>> hashmap = new HashMap<String, Set<String>>();
StringTokenizer st = new StringTokenizer(speech, ":");
while (st.hasMoreTokens()) {
String key = st.nextToken().trim();
String value = st.nextToken().trim();
StringTokenizer st1 = new StringTokenizer(value, "|");
while (st1.hasMoreTokens()) {
String a = st1.nextToken().trim();
if (!hashmap.containsKey(key))
hashmap.put(key, new HashSet<String>());
hashmap.get(key).add(a);
}
}
for (String key : hashmap.keySet())
System.out.printf("%s -> %s%n", key, hashmap.get(key));
}
}
You're overwriting the existing value when you call hashmap.put(key, a), since you're assigning a value to a key that already has a value.