java : remove words from ArrayList<String> - java

lets say my words Array is words={"a","the","in","if","are","it","is"} and my ArrayList contains strings like this {"a table is here", "books are sold","if it is readable"}. i want to remove all the words of array from the arrayList.
expected output would be ArrayList as {"table here","books sold","readable"}.
i have tried this so far :
public static void main(String[] args) {
String[] words = {"a","the","in","if","are","it","is"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));
String[] tArray = {"a table is here", "books are sold","if it is readable"};
List<String> list = new ArrayList<String>(Arrays.asList(tArray));
for (int i = 0; i < list.size(); i++) {
String[] tArrays = list.get(i).split(" ");
List<String> line = new ArrayList<String>(Arrays.asList(tArrays));
for (int c = 0; c < wordList.size(); c++) {
if (wordList.get(c).equals(line.get(i))) {
line.remove(i);
i--;
break;
}
}//end for
list.set(i, String.join(" ", line));
}//end for
for(String string : list)
{
System.out.println(string);
}
}
but not giving the expected output. instead gives an error "java.lang.ArrayIndexOutOfBoundsException: -1"

You should be using line.size() to iterate for all the words after splitting based on " ".
for (int i = 0; i < list.size(); i++) {
String[] tArrays = list.get(i).split(" ");
List<String> line = new ArrayList<>(Arrays.asList(tArrays));
for (int c = 0; c < wordList.size(); c++) {
if (wordList.get(c).equals(line.get(i))) { // you get i for indexes corresponding to the sentence element and not `line` elements as created above
line.remove(i); // i is iterated over the list of sentences in your case 3, would start from i=0
i--; // you change it to '-1' and get IndexOutOfBounds
break;
}
}//end for
list.set(i, String.join(" ", line));
}//end for
Though not tested, but you can do something like -
public static void main(String[] args) {
String[] words = {"a", "the", "in", "if", "are", "it", "is"};
List<String> wordList = new ArrayList<>(Arrays.asList(words));
String[] tArray = {"a table is here", "books are sold", "if it is readable"};
List<String> list = new ArrayList<>(Arrays.asList(tArray));
for (int i = 0; i < list.size(); i++) {
String[] tArrays = list.get(i).split(" ");
List<String> line = new ArrayList<>(Arrays.asList(tArrays));
for (String lineElement : line) {
if (wordList.contains(lineElement)) {
line.remove(lineElement);
}
}
list.set(i, String.join(" ", line));
}
for (String string : list) {
System.out.println(string);
}
}

Just to add the java 8 version of doing this kind of filtering:
String[] filtered =
list.stream().map(statement -> Arrays.asList(statement.split(" ")))
.map(listOfWords -> listOfWords.stream()
.filter(word -> !wordList.contains(word))
.collect(Collectors.joining(" "))
)
.toArray(String[]::new);
List<String> filteredList = Arrays.asList(filtered);
You can verify the output using:
filteredList.stream().forEach(System.out::println);
Hope this would be helpful!

Related

How to split strings of list into string array

I have a list that contains ("One.two.three", "one.two.four"). I want to save then in a string array as
One
two
three
one
two
four
What is the logic behind it?
You should be using java 8 to run this code. Just take those strings and split them on "."
split method of java need regex so to match "." you need "\.".Then transform array to list, then add words to list.
public static void main(String[] args) {
List<String> words = new ArrayList<String>();
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("one.two.four");
list.stream().forEach(str -> {
words.addAll(Arrays.asList(str.split("\\.")));
});
System.out.println(words.toString());
//output : [One, two, three, one, two, four]
}
For java 8+, you can use flatmap as -
String[] words = list.stream().flatMap(str -> Arrays.stream(str.split("\\."))).toArray(String[]::new);
If you are talking about the static arrays it is important to know array size to avoid "index is out of bounds" exception.
This way, I provide the solution that counts the number of words and then creates output s array to save every word.
We can use the String.split() function to get the single words we adding to output array:
String[] a = {"One.two.three", "one.two.four"};
int count = 0;
for (int i = 0; i < a.length; i++) { //skip this loop if you know the wanted array size
count += a[i].split("\\.").length;
}
String[] s = new String[count];
int k = 0;
for (int i = 0; i < a.length; i++) {
String[] b = a[i].split("\\.");
for (int j = 0; j < b.length; j++) {
s[k++] = b[j];
}
}
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
Try this.
FOR JAVA 1.8+
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
list.forEach(string -> {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
});
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}
UPTO JAVA 1.7
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
for (String string : list) {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
}
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}
If you are below Java 8 you can use this snippet:
public class Main {
public static void main(String[] args) throws Exception {
List<String> originalList = new ArrayList();
List<String> finalList = new ArrayList();
originalList.add("One.two.three");
originalList.add("One.two.four");
for(String myString : originalList) {
//The \\ is to scape the dot
finalList.addAll(Arrays.asList(myString.split("\\.")));
}
//Creates an array from the list
String[] theArray = finalList.toArray(new String[finalList.size()]);
}
}
Finally, theArray will contain:
[One, two, three, one, two, four]
Take a look at the docs about splitting an string into parts

How to split sentence in to words and then separate it in to two groups in Java?

I need to split sentence in to words and then in to two groups. One group should contain only last word in the sentence and other words belongs to second group as modifiers of the sentence.
Eg:
Max Price Food Information
{Max, Price, Food} {Information}
I did it until splitting the words. But cound't group like that.How can I do it?
import java.util.*;
public class Groupword {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<String>();
HashMap<String, Integer> wordFreqMap = new HashMap<String, Integer>();
terms.add("Max Price Food Information");
for(int i=0; i < terms.size(); i++) {
tempTerm = terms.get(i);
String[] result = tempTerm.split(" ");
for (String s : result) {
System.out.println("word="+s);
...................................
...................................
}
}
String lastWord = result[result.length - 1];
String[] modifiers = Arrays.copyOf(result, result.length - 1);
List<String> firstWordsList = new ArrayList<>();
List<String> lastWordList = new ArrayList<>();
for(String tempTerm : terms) {
int lastSpaceIndex = tempTerm.lastIndexOf(" ");
if (lastSpaceIndex >= 0) {
String firstWords = tempTerm.substring(0, lastSpaceIndex);
String lastWord = tempTerm.substring(lastSpaceIndex+1);
firstWordsList.add(firstWords);
lastWordsList.add(lastWord);
}
else {
lastWordsList.add(tempTerm);
}
}
Use Arrays.copyOfRange:
terms.add("Max Price Food Information");
for (String s: terms) {
String[] arr = s.split(" ");
String[] arr1 = Arrays.copyOfRange(arr, 0, arr.length-1); // [Max, Price, Food]
String[] arr2 = Arrays.copyOfRange(arr, arr.length-1, arr.length); // [Information]
}
i think this solution might work , it's not efficient
if you have this pattern :
Max Price Food Information
you could have two array :
String Data[][]=new String[3][terms.size];
String Information[] = new String[terms.size];
then reading data in following way :
Scanner in = new Scanner(System.in);
for(int i=0; i < terms.size(); i++){
Data[0][i] = in.next();
Data[1][i] = in.next();
Data[2][i] = in.next();
Information[i] = in.next();
}
this way is without split method
You can simply store the last word from the split words array and truncate the array's last element by copying it until length-1.
Something like this:
for(int i=0; i < terms.size(); i++) {
tempTerm = terms.get(i);
String[] result = tempTerm.split(" ");
for (String s : result) {
System.out.println("word="+s);
}
String lastWord = result[result.length-1];
result = Arrays.copyOf(result, result.length-1)
}

compare list and array

I need to compare the value from List with the value from array.
I wrote the following:
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
for (int i = 0; i < l.size(); i++){
v = "";
s = "";
//System.out.println(l.get(i));
for (int j = 0; j < arr.length; j++){
if (l.get(i).equals(arr[j])){
s = i + "";
}else{
s = arr[i];
}
v = v + s + ",";
}
System.out.println(v);
}
}
}
I obtain the following
0,test,test,
c,c,1
but I need the result like this:
0, c, 1,
Looking at your expected result I guess the requirement like that:
for each element in the array, check if it is on the list. If it is on the list, print the index from the list for this element, otherwise print the element itself. So the algorithm should do:
array[0] = "test" -> found at index 0 -> print "0"
array[1] = "c" -> not found -> print "c"
array[2] = "b" -> found at index 1 -> print "1"
The outer loop should iterate over the array. Then, for each array item, iterate over the list until you find the same element. For a first draft, don't collect the output in a string but print it immediatly. You can create the string when the algorithm works as expected.
You have six iterations, each of which inserts something into the output.
You want three iterations, each of which checks for membership in the first list. You can do that with the List.contains() method. (If the list were long, you might want to consider using a Set instead of a List, to allow checking set membership more quickly.)
How about this:
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
int pointer = 0;
for (int i = 0; i < l.size(); i++){
//System.out.println(l.get(i));
for (; pointer < arr.length;){
if (l.get(i).equals(arr[pointer])){
s = i + "";
v = v + s + ",";
pointer++;
break;
}else{
s = arr[i];
}
pointer++;
v = v + s + ",";
}
}
System.out.println(v);
}
Try to break things down to their high level steps.
For each string in the array
find its place in the list
if the item is in the list
print its position
else
print the missing string
print a common and space
Once you have this you can spot that find its place in the list could be a method that returns the place in the list or -1 if it isn't in the list. Here's what I made (might have renamed a few things and used a StringBuilder but you can ignore that for the moment).
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(final String[] args) {
final List<String> listToSeach = new ArrayList<String>();
listToSeach.add("test");
listToSeach.add("b");
final String[] arrayElementsToFind = { "test", "c", "b" };
final StringBuilder output = new StringBuilder();
for (final String string : arrayElementsToFind) {
final int firstIndex = findFirstIndex(listToSeach, string);
if (firstIndex > -1) {
output.append(firstIndex);
} else {
output.append(string);
}
output.append(", ");
}
System.out.println(output);
}
private static int findFirstIndex(final List<String> list,
final String element) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(element)) {
return i;
}
}
return -1;
}
}
Well I suggest this:
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String[] arr = {"test", "c", "b"};
for(int i=0;i<arr.length;++i){
if(l.contains(arr[i]))
s = ""+l.indexOf(arr[i]);
else
s = arr[i];
v = v + s + ",";
}
If got what you saying correct,I think this is less verbose

Generating String Tokens in Java

I want to generate possible tokens using forward traversal in Java. For example if I have a string "This is my car". I need to generate tokens
"This is my car"
"This is my"
"This is"
"This"
"is my car"
"is my"
"is"
"my car"
"my"
"car"
What is the best way to do this? Any examples? Thanks.
Here is another solution with split and nested loops:
public static void main(String[] args) {
String original = "this is my car";
String[] singleWords = original.split(" "); // split the String to get the single words
ArrayList<String> results = new ArrayList<String>(); // a container for all the possible sentences
for (int startWord = 0; startWord < singleWords.length; startWord++) { // starWords start with 0 and increment just until they reach the last word
for (int lastWord = singleWords.length; lastWord > startWord; lastWord--) { // last words start at the end and decrement just until they reached the first word
String next = "";
for (int i = startWord; i != lastWord; i++) { // put all words in one String (starting with the startWord and ending with the lastWord)
next += singleWords[i] + " ";
}
results.add(next); // add the next result to your result list
}
}
// this is just to check the results. All your sentences are now stored in the ArrayList results
for (String string : results) {
System.out.println("" + string);
}
}
and this was my result when I tested the method:
this is my car
this is my
this is
this
is my car
is my
is
my car
my
car
Use Guava:
String yourOriginalString = "This is my car";
final Set<String> originalWords =
Sets.newLinkedHashSet(
Splitter.on(CharMatcher.WHITESPACE).trimResults().split(yourOriginalString));
final Set<Set<String>> variations = Sets.powerSet(originalWords);
for (Set<String> variation : variations) {
System.out.println(Joiner.on(' ').join(variation));
}
Output:
This
is
This is
my
This my
is my
This is my
car
This car
is car
This is car
my car
This my car
is my car
This is my car
Here is a possible way:
//Just a method that seperates your String into an array of words based on the spaces
//I'll leave that for you to figure out how to make
String[] array = getSeperatedWords(<yourword>);
List<StringBuffer> bufferArray = new ArrayList<StringBuffer>();
for(int i = 0; i < array.length; i++){
StringBuffer nowWord = array[i];
for(int j = i; j < array.length; j++{
nowWord.append(array[j]);
}
bufferArray.add(nowWord);
}
for(int i = 0; i < bufferArray.length; i++){
System.out.print(bufferArray.get(i));
}
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String var = "This is my car";
permute(var);
}
public static void permute(String var) {
if(var.isEmpty())
return;
String[] arr = var.split(" ");
while(arr.length > 0) {
for(String str : arr) {
System.out.print(str + " ");
}
arr = (String[]) Arrays.copyOfRange(arr, 0, arr.length - 1);
System.out.println();
}
String[] original = var.split(" ");
permute(implodeArray((String[]) Arrays.copyOfRange(original, 1, original.length), " "));
}
public static String implodeArray(String[] inputArray, String glueString) {
String output = "";
if (inputArray.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append(inputArray[0]);
for (int i=1; i<inputArray.length; i++) {
sb.append(glueString);
sb.append(inputArray[i]);
}
output = sb.toString();
}
return output;
}
}
Read this book, you will be a master on recursion: http://mitpress.mit.edu/sicp/

How can you convert a 2 dimensional array into a 1 dimensional array in Java

I would like to know how to convert a 2 dimensional array into a 1 dimensional array. I have come up with some code but it doesn't exactly seem to work. Can someone please help me? Thanks.
public class TESTER1 {
/**
* #param args
*/
static String[][] data = new String[][] {{"Dum","Dumer","Dumbest"}};
public static void main(String[] args) {
convertData(data);
}
public static void convertData(String[][]data) {
String[] toReturn = new String[data.length];
for(int i = 0;i<data.length;i++) {
for(int j = 0;j<3;j++){
toReturn[i] = data[i][j];
}
}
for(String s:toReturn) {
System.out.println(s);
}
}
}
[edit]Thank you very much. Is it possible to convert each row in the String[][] into
a index in a String[] for example if we convert the String[][] (above code), then when
i print out array[0] it should print out dum,dummer,dumbest [edit]
public static String[] flatten(String[][] data) {
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < data.length; i++) {
for(int j = 0; j < data[i].length; j++){
list.add(data[i][j]);
}
}
return list.toArray(new String[0]);
}
Or add whole rows at one time:
for(int i = 0; i < data.length; i++) {
list.addAll( Arrays.asList(data[i]) );
}
Edit:
From comments on my answer it seems like this is what the OP wanted (i.e. converting each row of 2d array to some string representation of it):
public static String[] rowsToString(String[][] data) {
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < data.length; i++) {
String row = Arrays.toString(data[i]);
list.add( row.substring(1, row.length()-1) );
}
return list.toArray(new String[0]);
}
The length of the 1-dimensional array must be the sums of the lengths of all rows in the 2-dimensional array. Of course, Java doesn't really have "true" 2-dimensional arrays, but arrays of arrays. This code works, and is wrapped in a simple demo program.
public class ArrayFlattening {
public static final String[][] STRINGS2 = {
{"my", "dog", "has", "fleas"},
{"how", "now", "brown", "cow"},
{"short", "row"},
{"this", "is", "a", "final", "row", "in", "this", "test"},
};
public static String[] flatten(String[][] a2) {
String[] result = new String[totalSize(a2)];
int index = 0;
for (String[] a1 : a2) {
for (String s : a1) {
result[index++] = s;
}
}
return result;
}
public static int totalSize(String[][] a2) {
int result = 0;
for (String[] a1 : a2) {
result += a1.length;
}
return result;
}
public static void main(String[] args) {
System.out.println("" + STRINGS2.length + " rows");
for (String[] strings1 : STRINGS2) {
System.out.println("" + strings1.length + " strings");
for (String s : strings1) {
System.out.print("\t" + s);
}
System.out.println();
}
String[] strings1 = flatten(STRINGS2);
System.out.println(strings1.length + " strings");
for (String s : strings1) {
System.out.print("\t" + s);
}
System.out.println();
}
}
A cleaner version:
public static String[] flatten(String[][] data) {
List<String> toReturn = new ArrayList<String>();
for (String[] sublist : Arrays.asList(data)) {
for (String elem : sublist) {
toReturn.add(elem);
}
}
return toReturn.toArray(new String[0]);
}
Flatten did become much easier in Java 8 with the stream API. The function can be expressed as:
private static String[] flatten(String[][] data) {
return Stream.of(data).flatMap(Stream::of).toArray(String[]::new);
}

Categories

Resources