I'm trying to print out a collection of words to a CSV file and am trying to avoid spaces being printed as a word.
static TreeMap<String,Integer> wordHash = new TreeMap<String,Integer>();
Set words=wordHash.entrySet();
Iterator it = words.iterator();
while(it.hasNext()) {
Map.Entry me = (Map.Entry)it.next();
System.out.println(me.getKey() + " occured " + me.getValue() + " times");
if (!me.getKey().equals(" ")) {
ps.println(me.getKey() + "," + me.getValue());
}
}
Whenever I open the CSV, as well as in the console, the output is :
1
10 1
a 4
test 2
I am trying to remove that top entry of a space, I thought the statement checking if the key wasn't a space would work however it's still printing spaces. Any help is appreciated. Thanks.
Your condition will eliminate only single space keys. If you want to eliminate any number of empty spaces, use :
if (!me.getKey().trim().isEmpty()) {
...
}
This is assuming me.getKey() can't be null.
Related
I need to print all arraylist values at a time using concat.
Here is my code:
ArrayList<String> lst = new ArrayList<String>();
lst.add("hi");
lst.add("hello");
Iterator<String> itr = lst.iterator();
String result = null;
while(itr.hasNext()) {
Object element = itr.next();
result = element + " ";
}
System.out.println(result);
The expected result should be hi hello.
The current output however is hello (there is also a whitespace at the end).
Please prefer the List interface to the ArrayList concrete type. Assuming you are using Java 8+, you might use a Stream and Collectors.joining (and Arrays.asList) like
List<String> lst = Arrays.asList("hi", "hello");
String r = lst.stream().collect(Collectors.joining(" "));
System.out.println(r);
Which outputs
hi hello
As requested.
The error in your code is pretty small. In each iteration you assign a value to the result variable. However instead of updating your existing content you just erase it and enter a new value.
You do result = element + " ". But it should be something like result = result + element + " " or the same in short:
result += element + " ";
This way the first iteration will save hi in it and after that hello gets appended resulting in hi hello (instead of overriding the content of the first iteration).
Note that it now also has the whitespace at the end. You could delete it with result = result.substring(0, result.length() - 1). Or not add it in the last iteration, but then you need to count the iterations.
Please note that Java has a class StringJoiner that does exactly what you want, joining some elements together and also using a delimiter like whitespace. You use it like this:
StringJoiner sj = new StringJoiner(" ");
while(itr.hasNext()) {
Object element = itr.next();
sj.add(element);
}
String result = sj.toString();
Also note that since Java 8 there is an even shorter version of it:
String result = String.join(" ", list);
I'm building a small app which auto translates boolean queries in Java.
This is the code to find if the query string contains a certain word and if so, it replaces it with the translated value.
int howmanytimes = originalValues.size();
for (int y = 0; y < howmanytimes; y++) {
String originalWord = originalValues.get(y);
System.out.println("original Word = " + originalWord);
if (toReplace.contains(" " + originalWord.toLowerCase() + " ")
|| toCheck.contains('"' + originalWord.toLowerCase() + '"')) {
toReplace = toReplace.replace(originalWord, translatedValues.get(y).toLowerCase());
System.out.println("replaced " + originalWord + " with " + translatedValues.get(y).toLowerCase());
}
System.out.println("to Replace inside loop " + toReplace);
}
The problem is when a query has, for example, '(mykeyword OR "blue mykeyword")' and the translated values are different, for example, mykeyword translates to elpalavra and "blue mykeyword" translates to "elpalavra azul". What happens in this case is that the result string will be '(elpalavra OR "blue elpalavra")' when it should be '(elpalavra OR "elpalavra azul")' . I understand that in the first loop it replaces all keywords and in the second it no longer contains the original value it should for translation.
How can I fix this?
Thank you
you can sort originalValues by size desc. And after that loop through them.
This way you first replace "blue mykeyword" and only after you replace "mykeyword"
The "toCheck" variable is not explained what is for, and in any case the way it is used looks weird (to me at least).
Keeping that aside, one way to answer your request could be this (based only on the requirements you specified):
sort your originalValues, so that the ones with more words are first. The ones that have same number of words, should be ordered from more length to less.
I have created a hashmap the contains a string for the key and and an object as the value. However, when I try to retrieve some of the values, I get a null result.
// This returns all the keys and their values.
for (String key : DevicesUsed.devicesUsedMap.keySet()) {
if(DevicesUsed.devicesUsedMap.containsKey(key)) {
System.out.println(key + " exists");
System.out.println(key + "\t" + DevicesUsed.devicesUsedMap.get(key));
} else {
System.out.println("Key does not exist.");
}
}
// This only works for some of the keys, that worked in the above code.
System.out.println(DevicesUsed.devicesUsedMap.get("WHITEALL")); // Works.
System.out.println(DevicesUsed.devicesUsedMap.get("REDCOVE")); // Returns null.
screen shot of the console output
Very confused as to why some of the keys exist in one block, but not in the other.
On your screenshot message 'WHITEALL exist' contains one space, but 'REDCOVE exist' - two.
It looks like you have 'REDCOVE ' as key instead of 'REDCOVE'.
From you screenshot REDCOVE definitely has a space at the end. Try using System.out.println(DevicesUsed.devicesUsedMap.get("REDCOVE "));
How to achieve:
compare a element from a collection (don't know the index, so can use contains/equals to compare string value), check if exist then have to add some characters to that string value (will be picked up from somewhere else) and then add it back to the collection be be the last element.
Example scenario:
xyz<Collection> contains these values:
"abc"
"hgj"
"jsh"
"yjk"
if (xyz.contains("jsh")){
then concat "jsh" + " " + randomOtherStuff
And put it back in the collection to be last element so when printed the order is
"abc"
"hgj"
"yjk"
"jsh + " " + randomOtherStuff"
}
Thank you for all help, in advance :D
if (collection.contains("jsh")) {
collection.remove("jsh"); // remove it, so it can be re-added to the end
collection.add("jsh " + "asdfgdfgsdfhsjdfh"); // add the new string + some random stuff to the end of the list
}
Code:public class duplicate
{
public static void main(String[] args)throws IOException
{
System.out.println("Enter words separated by spaces ('.' to quit):");
Set<String> s = new HashSet<String>();
Scanner input = new Scanner(System.in);
while (true)
{
String token = input.next();
if (".".equals(token))
break;
if (!s.add(token))
System.out.println("Duplicate detected: " + token);
}
System.out.println(s.size() + " distinct words:\n" + s);
Set<String> duplicatesnum = new HashSet<String>();
String token = input.next();
if (!s.add(token))
{
duplicatesnum.add(token);
System.out.println("Duplicate detected: " + token);
}
System.out.println(duplicatesnum.size());
}
}
the output is:
Enter words separated by spaces ('.' to quit):
one two one two .
Duplicate detected: one
Duplicate detected: two
2 distinct words:
[two, one]
I assume you want to know the number of different duplicate words. You can use another HashSet<String> for the duplicates.
//Outside the loop
Set<String> duplicates = new HashSet<String>();
//Inside the loop
if (!s.add(token))
{
duplicates.add(token);
System.out.println("Duplicate detected: " + token);
}
//Outside the loop
System.out.println(duplicates.size());
Also if you care for the occurences of each word declare a HashMap<String, Integer> as in others posts is mentioned.
But if you want the number of all duplicate words(not different) just declare a counter:
//Outside the loop
int duplicates = 0;
//Inside the loop
if (!s.add(token))
{
duplicates++;
System.out.println("Duplicate detected: " + token);
}
//Outside the loop
System.out.println(duplicates);
Instead of a HashSet, use a HashMap. A HashSet only stores the values. A HashMap maps a value to another value (see http://www.geekinterview.com/question_details/47545 for an explanation)
In your case, the key of the HashMap is your string (just as the key of the HashSet is the string). The value in the HashMap is the number of times you encountered this string.
When you find a new string, add it to the HashMap, and set the value of the entry to zero.
When you encounter the same string later, increment the value in the HashMap.
Because you are using a HashSet, you will not know how many duplicates you have. If you went with a HashMap<String, Integer>, you could increment whenever you found that your key was != null.
In the if (!s.add(token)), you can increment a counter and then display it's value at the end.
Your question is a bit misleading. Some people understand that you want:
Input: hello man, hello woman, say good by to your man.
Output:
Found duplicate: Hello
Found duplicate: Man
Duplicate count: 2
Others understood you wanted:
Input: hello man, hello woman, say hello to your man.
Output:
Found duplicate: Hello - 3 appearances
Found duplicate: Man - 2 appearances
Assuming you want the 1st option - go with Petar Minchev's solution
Assuming you want the 2nd option - go with Patrick's solution. Don't forget that when you use an Integer in a Map, you can get/put int as well, and Java will Automatically Box/Unbox it for you, but if you rely on this - you can get NPEs when asking the map for a key that does not exist:
Map<String,Integer> myMap = new HashMap<String,Integer>();
myMap.get("key that does not exist"); // NPE here <---
The NPE is caused since the return value from 'get' is null, and that value is being cast into an Integer after which the intValue() method will be invoked - thus triggering an NPE.
You can use Google collections library:
Multiset<String> words = HashMultiset.create();
while (true) {
String token = input.next();
if (".".equals(token))
break;
if (!words.add(token))
System.out.println("Duplicate detected: " + token);
}
System.out.println(words.elementSet().size() + " distinct words:\n" + words.elementSet());
Collection<Entry<String>> duplicateWords = Collections2.filter(words.entrySet(), new Predicate<Entry<String>>() {
public boolean apply(Entry<String> entry) {
return entry.getCount() > 1;
}
});
System.out.println("There are " + duplicateWords.size() + " duplicate words.");
System.out.println("The duplicate words are: " + Joiner.on(", ").join(duplicateWords));
Example of output:
Enter words separated by spaces ('.' to quit):
aaa bbb aaa ccc aaa bbb .
3 distinct words:
[aaa, ccc, bbb]
There are 2 duplicate words.
The duplicate words are: aaa x 3, bbb x 2