Remove String from list if certain character missing - java

I have a list of words ["home", "shop", "salmon", "time"] and I have a scrambled String "ahlowemr". I want to check if each word in the list has characters from this scrambled String and remove the word from list if it doesn't contain all the characters.
In this example, less "home", the remaining 3 Strings should be removed. I tried to loop as follows but it doesn't allow me to check characters. And I am nesting loops which I think is not a good idea. Is there any way around this?
ArrayList<String> myList = new ArrayList<String>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
for(String s : myList){
for(char c : scrambled.toCharArray()){
if(!s.contains(c)){ //doesn't allow character c
myList.remove(s);
}
}
}

If you want to remove items from a list while you iterate it, you should use an Iterator, also, the contains(...) method expects a String, not a char.
Here is what you can do:
for(Iterator<String> it = myList.iterator(); it.hasNext();){
String s = it.next();
for(char c : scrambled.toCharArray()){
if(!s.contains(String.valueOf(c))){
it.remove();
break;
}
}
}

ArrayList<String> myList = new ArrayList<String>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
for(int i = 0; i < myList.size(); i++) {
for(char c : scrambled.toCharArray()){
if(!myList.get(i).contains(c.toString())){ //doesn't allow character in that position
// There is a simple way using a regex or maybe a hashtable
myList.remove(s);
break; // break will jump into the next list value
}
}
}

java-8 solution for completeness:
ArrayList<String> myList = new ArrayList<>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
myList = myList.stream()
.filter(s -> scrambled.chars()
.allMatch(c -> s.contains(String.valueOf((char) c))))
.collect(Collectors.toCollection(ArrayList<String>::new));

Related

typical operations on stored string in java

What is the Best Data Structure availaible in java to Store strings and then do some operations on it as such as:(Beginner in Java)
Input: Sam Mohit Laksh Nitesh Aquib
i know i can store each of them in data structures as such as ArrayList and etc.
But if i store them as:
Scanner sc= new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
then iterating and adding them as:
for(int i=0;i<n;i++)
//let n be any number
{
List.add(sc.next());
}
but What if i want to Convert a Word Like Mohit to as a char array as ['M','o','h','i','t']
so that char[0]='M' or char[3]='i'
i know i can iterate through an iterator object of type MyArrayList. but can that iterator be converted to char array ?
but can that iterator be converted to char array ?
Yes Iterator#next() will give you string (because List has generic type String) that can be used to perform any kind of string operation. See the code below put it in main method and run.
String[] str = {"Sam", "Mohit", "Laksh", "Nitesh"};
List<String> list = new ArrayList<String>();
for(int i=0;i<str.length;i++)
{
list.add(str[i]);
}
Iterator<String> iter = list.iterator();
while(iter.hasNext()){
//here apply some condition to get your specific string object
char[] chars = iter.next().toCharArray();
System.out.println(chars);
}
I would propose ArrayList and streams for transforming in something else :
List<String> words = new ArrayList<>();
words.add("John");
words.add("Mohito");
Transformation List<String> to List<char[]>:
List<char[]> asChar = words.stream()
.map(String::toCharArray)
.collect(Collectors.toList());
For transforming char[] to List<Character>:
char[] cc = new char[]{'a', 'b'};
List<Character> collect1 = String.valueOf(cc)
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.toList());
Getting char from List:
String letter = collect1.get(0).toString();

Java: Removing item from array because of character

Lets say you have an array like this: String[] theWords = {"hello", "good bye", "tomorrow"}. I want to remove/ignore all the strings in the array that have the letter 'e'. How would I go about doing that? My thinking is to go:
for (int arrPos = 0; arrPos < theWords.length; arrPos++) { //Go through the array
for (int charPos = 0; charPos < theWords[arrPos].length(); charPos++) { //Go through the strings in the array
if (!((theWords[arrPos].charAt(charPos) == 'e')) { //Finds 'e' in the strings
//Put the words that don't have any 'e' into a new array;
//This is where I'm stuck
}
}
}
I'm not sure if my logic works and if I'm even on the right track. Any responses would be helpful. Many thanks.
One easy way to filter an array is to populate an ArrayList with if in a for-each loop:
List<String> noEs = new ArrayList<>();
for (String word : theWords) {
if (!word.contains("e")) {
noEs.add(word);
}
}
Another way in Java 8 is to use Collection#removeIf:
List<String> noEs = new ArrayList<>(Arrays.asList(theWords));
noEs.removeIf(word -> word.contains("e"));
Or use Stream#filter:
String[] noEs = Arrays.stream(theWords)
.filter(word -> !word.contains("e"))
.toArray(String[]::new);
You can directly use contains() method of String class to check if "e" is present in your string. That will save your extra for loop.
It would be simple if you use ArrayList.
importing import java.util.ArrayList;
ArrayList<String> theWords = new ArrayList<String>();
ArrayList<String> yourNewArray = new ArrayList<String>;//Initializing you new array
theWords.add("hello");
theWords.add("good bye");
theWords.add("tommorow");
for (int arrPos = 0; arrPos < theWords.size(); arrPos++) { //Go through the array
if(!theWords.get(arrPos).contains("e")){
yourNewArray.add(theWords.get(arrPos));// Adding non-e containing string into your new array
}
}
The problem you have is that you need to declare and instantiate the String array before you even know how many elements are going to be in it (since you wouldn't know how many strings would not contain 'e' before going through the loop).
Instead, if you use an ArrayList you do not need to know the required size beforehand. Here is my code from start to end.
String[] theWords = { "hello", "good bye", "tomorrow" };
//creating a new ArrayList object
ArrayList<String> myList = new ArrayList<String>();
//adding the corresponding array contents to the list.
//myList and theWords point to different locations in the memory.
for(String str : theWords) {
myList.add(str);
}
//create a new list containing the items you want to remove
ArrayList<String> removeFromList = new ArrayList<>();
for(String str : myList) {
if(str.contains("e")) {
removeFromList.add(str);
}
}
//now remove those items from the list
myList.removeAll(removeFromList);
//create a new Array based on the size of the list when the strings containing e is removed
//theWords now refers to this new Array.
theWords = new String[myList.size()];
//convert the list to the array
myList.toArray(theWords);
//now theWords array contains only the string(s) not containing 'e'
System.out.println(Arrays.toString(theWords));

How to create vocabulary from Arrays of Strings

I have to make a vocabulary with unique words of some texts. I have texts converted to Arrays of Strings. Now I want the Array list with only unique words. So the first step, convert the first Array of Strings to a List<Strings> (I guess?) where all double words are filtered out. That is my first step, how do I do this, and do I use a List<String> or another String[]?
Second, the next String[] I 'read-in' should update the vocabulary List<String> but ONLY add new words from the text.
It must look something like:
public List<String> makeVocabulary(String[] tokens){
List<String> vocabulay = new ArrayList<>;
//add unique words from 'tokens' to vocabulary
return vocabulary;
}
TL;DR: how do I convert a whole bunch of String[] to one List<String> with only the unique words from the String[]'s?
Upon review of your code, it appears that you would be clearing vocabulary each time you run this command, so it can only be done once. If you'd like to make it more modular, do something like this:
public class yourClass
{
private List<String> vocabulary = new ArrayList<String>();
public List<String> makeVocabulary(String[] tokens)
{
for( int i = 0; i < tokens.length; i++ )
if( !vocabulary.contains( tokens[i] ) )
vocabulary.add(tokens[i]);
return vocabulary;
}
}
For determining unique tokens, use a Set implementation...
public List<String> makeVocabulary(String[] tokens){
Set<String> uniqueTokens = new HashSet<String>();
for(String token : tokens) {
uniqueTokens.add(token);
}
List<String> vocabulay = new ArrayList<String>(uniqueTokens);
return vocabulary;
}
One way to achieve your goal is to make use of the Set class as opposed to a List of strings. You could look into that e.g. like the code below.
public List<String> makeVocabulary(String[] tokens){
Set<String> temp = new HashSet<>;
//add unique words from 'tokens' to temp
List<String> vocabulary = new ArrayList<>;
vocabulary.addAll(temp);
return vocabulary;
}
If you can live with Set as the return type of makeVocabulary, you can just return temp.

Comparison of two lists in java using for loop

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);

string compare in java

I have a ArrayList, with elements something like:
[string,has,was,hctam,gnirts,saw,match,sah]
I would like to delete the ones which are repeating itself, such as string and gnirts, and delete the other(gnirts). How do I go about achieving something as above?
Edit: I would like to rephrase the question:
Given an arrayList of strings, how does one go about deleting elements containing reversed strings?
Given the following input:
[string,has,was,hctam,gnirts,saw,match,sah]
How does one reach the following output:
[string,has,was,match]
Set<String> result = new HashSet<String>();
for(String word: words) {
if(result.contains(word) || result.contains(new StringBuffer(word).reverse().toString())) {
continue;
}
result.add(word);
}
// result
You can use a comparator that sorts the characters before checking them for equality. This means that compare("string", "gnirts") will return 0. Then use this comparator as you traverse through the list and copy the matching elements to a new list.
Another option (if you have a really large list) is to create an Anagram class that extends the String class. Override the hashcode method so that anagrams produce the same hashcode, then use a hashmap of anagrams to check your array list for anagrams.
HashSet<String> set = new HashSet<String>();
for (String str : arraylst)
{
set.add(str);
}
ArrayList<String> newlst = new ArrayList<String>();
for (String str : arraylst)
{
if(!set.contains(str))
newlst.add(str);
}
To remove duplicate items, you can use HashMap (), where as the key codes will be used by the sum of the letters (as each letter has its own code - is not a valid situation where two different words have an identical amount of code numbers), as well as the value - this the word. When adding a new word in a HashMap, if the amount of code letters of new words is identical to some of the existing key in a HashMap, then the word with the same key is replaced by a new word. Thus, we get the HashMap collection of words without repetition.
With regard to the fact that the bottom line "string" looks better "gnirts". It may be a situation where we can not determine which word is better, so the basis has been taken that the final form of the word is not important - thing is that there are no duplicate
ArrayList<String> mainList = new ArrayList<String>();
mainList.add("string,has,was,hctam,gnirts,saw,match,sah");
String[] listChar = mainList.get(0).split(",");
HashMap <Integer, String> hm = new HashMap<Integer, String>();
for (String temp : listChar) {
int sumStr=0;
for (int i=0; i<temp.length(); i++)
sumStr += temp.charAt(i);
hm.put(sumStr, temp);
}
mainList=new ArrayList<String>();
Set<Map.Entry<Integer, String>> set = hm.entrySet();
for (Map.Entry<Integer, String> temp : set) {
mainList.add(temp.getValue());
}
System.out.println(mainList);
UPD:
1) The need to maintain txt-file in ANSI
In the beginning, I replaced Scaner on FileReader and BufferedReader
String fileRStr = new String();
String stringTemp;
FileReader fileR = new FileReader("text.txt");
BufferedReader streamIn = new BufferedReader(fileR);
while ((stringTemp = streamIn.readLine()) != null)
fileRStr += stringTemp;
fileR.close();
mainList.add(fileRStr);
In addition, all the words in the file must be separated by commas, as the partition ishonoy lines into words by the function split (",").
If you have words separated by another character - replace the comma at the symbol in the following line:
String[] listChar = mainList.get(0).split(",");

Categories