I'm trying to get this to return a certain number of array entries based on their containing a certain input string.
/**
* This method returns a list of all words from
* the dictionary that include the given substring.
*/
public ArrayList<String> wordsContaining(String text)
{
ArrayList<String> contentCheck = new ArrayList<String>();
for(int index = 0; index < words.size(); index++)
{
if(words.contains(text))
{
contentCheck.add(words.get(index));
}
}
return contentCheck;
}
I don't understand why this keeps returning freaking every value in the array instead of only the entries containing the string bit.
Thanks!
Your condition:
if(words.contains(text))
checks whether the text is in the list or not. That would be true for all or none of the elements.
What you want is:
if(words.get(index).contains(text))
Apart from that, it would be better if you use enhanced for statement:
for (String word: words) {
if(word.contains(text)) {
contentCheck.add(word);
}
}
You have 2 issues in your code
The first one is one is that You check in your condition
if(words.contains(text)) - this check that text is in list
and what you probably want is to check that given item of list contains text
public List<String> wordsContaining(String text)
{
List<String> contentCheck = new ArrayList<String>();
for(String word : words) //For each word in words
{
if(word.contains(text)) // Check that word contains text
{
contentCheck.add(word);
}
}
return contentCheck;
}
Related
We have to find all simple words from a bunch of simple and compound words. For example:
Input: chat, ever, snapchat, snap, salesperson, per, person, sales, son, whatsoever, what so.
Output should be: chat, ever, snap, per, sales, son, what, so
My sample code:
private static String[] find(String[] words) {
// TODO Auto-generated method stub
//System.out.println();
ArrayList<String> alist = new ArrayList<String>();
Set<String> r1 = new HashSet<String>();
for(String s: words){
alist.add(s);
}
Collections.sort(alist,new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.length()-o2.length();
}
});
//System.out.println(alist.toString());
int count= 0;
for(int i=0;i<alist.size();i++){
String check = alist.get(i);
r1.add(check);
for(int j=i+1;j<alist.size();j++){
String temp = alist.get(j);
//System.out.println(check+" "+temp);
if(temp.contains(check) ){
alist.remove(temp);
}
}
}
System.out.println(r1.toString());
String res[] = new String[r1.size()];
for(String i:words){
if(r1.contains(i)){
res[count++] = i;
}
}
return res;
}
I am unable to get a solution with the above code. Any suggestions or ideas
compound word = concatenation of two or more words;rest all words are considered as simple words
We have to remove all the compound words
Algorithm
Read the input into a set of Strings i.e. Set<String> input
Create a empty set for simple words i.e. Set<String> simpleWords
Create a empty set for compound words i.e. Set<String> compoundWords
Iterate over input. For each element
Let length of element be elemLength
Create a set Set<String> inputs of all Strings from the set input (excluding element) for which the below is true
Length less than element
Not present in compundWords
Create set of all permutations of inputs(by concatenating) with max length = elemLength i.e. Set<String> currentPermutations
See if any of currentPermutations is = element
If yes, add element into compoundWords
If no, continue with iteration
After the iteration is done place all Strings from input which are not present in compoundWords into simpleWords
That is your answer.
Before you start writing code decide the logic that you are going to use. Use descriptive variable names and you are basically done.
The reason your logic is not working has to do with the way you are checking temp.contains(check). This is checking for substring not a compound word as per your definition.
I am trying to show the list of words which start with the letter specified by the user input.
So for example if I add three words to my list, cat, corn and dog, and the user inputs the letter c, the output on the Java applet should be cat, corn.
However, I have no idea on how to go about this.
public void actionPerformed(ActionEvent e){
if (e.getSource() == b1 ){
x = textf.getText();
wordList.add(x);
textf.setText(null);
}
if (e.getSource() == b2 ){
}
}
b1 is adding all the user input into a secretly stored list, and I now want to make another button when pressed to show the words that start with the specified letter by the user.
textf = my text field
wordList = my list I created
x = string I previously defined
You could loop through all the possible indices, check if the element at that index starts with the letter, and print it if it does.
ALTERNATIVE (and probably better) code (I was going to put this after, but since its better it deserves to be first. Taken form #larsmans's answer here.
//given wordList as the word list
//given startChar as the character to search for in the form of a *String* not char
for (String element : wordList){
if (element.startsWith(startChar)){
System.out.println(element);
}
}
DISCLAIMER: This code is untested, I don't have much experience with ArrayList, and Java is more of a quaternary programming language for me. Hope it works :)
//given same variables as before
for (int i = 0; i < wordList.size(); i++){
String element = wordList.get(i);
//you could remove the temporary variable and replace element with
// wordList.get(i)
if (element.startsWith(startChar){
System.out.println(element);
}
}
You can try something like this -
public static void main(String[] args) {
String prefix = "a";
List<String> l = new ArrayList<String>();
List<String> result = new ArrayList<String>();
l.add("aah");
l.add("abh");
l.add("bah");
for(String s: l) {
if(s.startsWith(prefix)) {
result.add(s);
}
}
System.out.println(result);
}
Result is -
[aah, abh]
If you can use Java 8 then you can build in features to filter your list:
public static void main(String[] args) throws Exception {
final List<String> list = new ArrayList<>();
list.add("cat");
list.add("corn");
list.add("dog");
System.out.println(filter(list, "c"));
}
private static List<String> filter(final Collection<String> source, final String prefix) {
return source.stream().filter(item -> item.startsWith(prefix)).collect(Collectors.toList());
}
This uses the filter method to filter each list item which starts with the String of the prefix argument.
The output is:
[cat, corn]
I have a List of Strings, and most of them are multiple words:
"how are you"
"what time is it"
I want to remove the space from every string in this list:
"howareyou"
"whattimeisit"
I know of the Collections.replaceAll(list, to replace, replace with), but that only applies to Strings that are that exact value, not every instance in every String.
What you must is to apply the replace function to each of the string in your list.
And as the strings are immutable you will have to create another list where string with no space will be stored.
List<String> result = new ArrayList<>();
for (String s : source) {
result.add(s.replaceAll("\\s+", ""));
}
Immutable means that object can not be changed, it must be created new one if you want to change the state of it.
String s = "how are you";
s = s.replaceAll("\\s+", "");
The function replaceAll returns the new string if you did not assign it to variable s then would still have spaces.
It doesn't sound very useful.
But try this:
import java.util.Arrays;
import java.util.List;
/**
* http://stackoverflow.com/questions/20760578/how-do-i-replace-characters-in-every-string-in-my-list-in-java/20760659#20760659
* Date: 12/24/13
* Time: 7:08 AM
*/
public class SpaceEater {
public static void main(String[] args) {
List<String> stringList = Arrays.asList(args);
System.out.println("before: " + stringList);
for (int i = 0; i < stringList.size(); ++i) {
stringList.set(i, stringList.get(i).replaceAll("\\s+", ""));
}
System.out.println("after : " + stringList);
}
}
disrvptor was correct - original snippet did not alter the list. This one does.
You can try this:
No need to define new array list. Use list.set this set replaces the element at the specified position in this list with the specified element.
int i = 0;
for (String str : list)
{
list.set(i, str.replaceAll(" ", ""));
i++;
}
Output
for (String s : list)
{
System.out.println(s);
}
//Thisisastring
//Thisisanotherstring
The only way I know how to do this is to iterate over the list, perform the replace operation on every object and replace the original object with the new one. This is best handled with 2 lists (source and target).
I have two list word containing words (word is a copy of the list words) and existingGuesses containing characters and I want to compare them (means compare whether each character is present in the list word or not) by iterating through a for loop. Can anybody suggest me how to do the comparison?
public List<String> getWordOptions(List<String> existingGuesses, String newGuess)
{
List<String> word = new ArrayList<String>(words);
/* String c = existingGuesses.get(0);
ListIterator<String> iterator = word.listIterator();
while(iterator.hasNext()){
if(word.contains(c))
{
word.remove(c);
}
}*/
for(String temp: word){
for(String cha: existingGuesses){
}
}
return null;
}
You can check for the guesses in words like this by using the List#contains(Object).
for(String myGuess: existingGuesses){
if(word.contains(myGuess)) {
// Do what you want
}
}
How about the following O(N) complexity code
public List<String> getWordOptions(List<String> existingGuesses, String newGuess) {
List<String> word = new ArrayList<String>(words);
for (String cha : existingGuesses) {
if (word.contains(cha)) {
word.remove(cha);
}
}
return null;
}
If you want to compare them and remove them if its there,
Then You can use the List#removeAll(anotherlist)
Removes from this list all of its elements that are contained in the specified collection (optional operation).
(Got clue from word.remove(c);) from your commented code.
You can use Collection.retainAll:
List<String> word=new ArrayList<String>();//fill list
List<String> existingGuesses=new ArrayList<String>();//fill list
List<String> existingWords=new ArrayList<String>(word);
existingWords.retainAll(existingGuesses);
//existingWords will only contain the words present in both the lists
System.out.println(existingWords);
I have to count the number of unique words from a text document using Java. First I had to get rid of the punctuation in all of the words. I used the Scanner class to scan each word in the document and put in an String ArrayList.
So, the next step is where I'm having the problem! How do I create a method that can count the number of unique Strings in the array?
For example, if the array contains apple, bob, apple, jim, bob; the number of unique values in this array is 3.
public countWords() {
try {
Scanner scan = new Scanner(in);
while (scan.hasNext()) {
String words = scan.next();
if (words.contains(".")) {
words.replace(".", "");
}
if (words.contains("!")) {
words.replace("!", "");
}
if (words.contains(":")) {
words.replace(":", "");
}
if (words.contains(",")) {
words.replace(",", "");
}
if (words.contains("'")) {
words.replace("?", "");
}
if (words.contains("-")) {
words.replace("-", "");
}
if (words.contains("‘")) {
words.replace("‘", "");
}
wordStore.add(words.toLowerCase());
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
}
System.out.println("The total number of words is: " + wordStore.size());
}
Are you allowed to use Set? If so, you HashSet may solve your problem. HashSet doesn't accept duplicates.
HashSet noDupSet = new HashSet();
noDupSet.add(yourString);
noDupSet.size();
size() method returns number of unique words.
If you have to really use ArrayList only, then one way to achieve may be,
1) Create a temp ArrayList
2) Iterate original list and retrieve element
3) If tempArrayList doesn't contain element, add element to tempArrayList
Starting from Java 8 you can use Stream:
After you add the elements in your ArrayList:
long n = wordStore.stream().distinct().count();
It converts your ArrayList to a stream and then it counts only the distinct elements.
I would advice to use HashSet. This automatically filters the duplicate when calling add method.
Although I believe a set is the easiest solution, you can still use your original solution and just add an if statement to check if value already exists in the list before you do your add.
if( !wordstore.contains( words.toLowerCase() )
wordStore.add(words.toLowerCase());
Then the number of words in your list is the total number of unique words (ie: wordStore.size() )
This general purpose solution takes advantage of the fact that the Set abstract data type does not allow duplicates. The Set.add() method is specifically useful in that it returns a boolean flag indicating the success of the 'add' operation. A HashMap is used to track the occurrence of each original element. This algorithm can be adapted for variations of this type of problem. This solution produces O(n) performance..
public static void main(String args[])
{
String[] strArray = {"abc", "def", "mno", "xyz", "pqr", "xyz", "def"};
System.out.printf("RAW: %s ; PROCESSED: %s \n",Arrays.toString(strArray), duplicates(strArray).toString());
}
public static HashMap<String, Integer> duplicates(String arr[])
{
HashSet<String> distinctKeySet = new HashSet<String>();
HashMap<String, Integer> keyCountMap = new HashMap<String, Integer>();
for(int i = 0; i < arr.length; i++)
{
if(distinctKeySet.add(arr[i]))
keyCountMap.put(arr[i], 1); // unique value or first occurrence
else
keyCountMap.put(arr[i], (Integer)(keyCountMap.get(arr[i])) + 1);
}
return keyCountMap;
}
RESULTS:
RAW: [abc, def, mno, xyz, pqr, xyz, def] ; PROCESSED: {pqr=1, abc=1, def=2, xyz=2, mno=1}
You can create a HashTable or HashMap as well. Keys would be your input strings and Value would be the number of times that string occurs in your input array. O(N) time and space.
Solution 2:
Sort the input list.
Similar strings would be next to each other.
Compare list(i) to list(i+1) and count the number of duplicates.
In shorthand way you can do it as follows...
ArrayList<String> duplicateList = new ArrayList<String>();
duplicateList.add("one");
duplicateList.add("two");
duplicateList.add("one");
duplicateList.add("three");
System.out.println(duplicateList); // prints [one, two, one, three]
HashSet<String> uniqueSet = new HashSet<String>();
uniqueSet.addAll(duplicateList);
System.out.println(uniqueSet); // prints [two, one, three]
duplicateList.clear();
System.out.println(duplicateList);// prints []
duplicateList.addAll(uniqueSet);
System.out.println(duplicateList);// prints [two, one, three]
public class UniqueinArrayList {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer();
List al=new ArrayList();
al.add("Stack");
al.add("Stack");
al.add("over");
al.add("over");
al.add("flow");
al.add("flow");
System.out.println(al);
Set s=new LinkedHashSet(al);
System.out.println(s);
Iterator itr=s.iterator();
while(itr.hasNext()){
sb.append(itr.next()+" ");
}
System.out.println(sb.toString().trim());
}
}
3 distinct possible solutions:
Use HashSet as suggested above.
Create a temporary ArrayList and store only unique element like below:
public static int getUniqueElement(List<String> data) {
List<String> newList = new ArrayList<>();
for (String eachWord : data)
if (!newList.contains(eachWord))
newList.add(eachWord);
return newList.size();
}
Java 8 solution
long count = data.stream().distinct().count();