This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
If i have an array of strings, for example, String[] myS = new String[] {"1234", "abcd", "234", "bcd", "34", "cd"}, will sort work on this? I assumed sort on strings would sort it alphabetically, but if so, would it break once it sees a string containing numerical digits?
Here's my function (which is taking in 2 string arrays and doing a substring comparison of 1 and 2.)
public static String[] inArray(String[] array1, String[] array2) {
if(array1.length == 0 || array2.length == 0) return new String[]{};
int size=0, index = 0;
Boolean flag = false;
for(int i=0; i<array1.length; i++){
flag = false;
for(int j=0; j<array2.length; j++){
if(array2[j].contains(array1[i])){
flag = true;
break;
}
}
if(flag == false) array1[i] = "";
else size++;
}
if(size == 0) return new String[] {}; //No matches found
String[] sortedArr = new String[size];
for(int i = 0; i<size; i++){
if(array1[i] != ""){
sortedArr[index] = array1[i];
index++;
}
}
Arrays.sort(sortedArr); //Occasionally throws null pointer exception
return sortedArr;
}
Nope, a "String containing numerical digits" si also a String...
Sorting is generally based on Unicode codepoints, thus numbers would sort before letters.
Related
currently I'm trying to make a method that does the following:
Takes 3 String Arrays (words, beforeList, and afterList)
Looks for words that are in both words and in beforeList, and if found, replaces with word in afterList
Returns a new array that turns the elements with characters in afterList into new elements by themselves
For example, here is a test case, notice that "i'm" becomes split into two elements in the final array "i" and "am":
String [] someWords = {"i'm", "cant", "recollect"};
String [] beforeList = {"dont", "cant", "wont", "recollect", "i'm"};
String [] afterList = {"don't", "can't", "won't", "remember", "i am"};
String [] result = Eliza.replacePairs( someWords, beforeList, afterList);
if ( result != null && result[0].equals("i") && result[1].equals("am")
&& result[2].equals("can't") && result[3].equals("remember")) {
System.out.println("testReplacePairs 1 passed.");
} else {
System.out.println("testReplacePairs 1 failed.");
}
My biggest problem is in accounting for this case of whitespaces. I know the code I will post below is wrong, however I've been trying different methods. I think my code right now should return an empty array that is the length of the first but accounted for spaces. I realize it may require a whole different approach. Any advice though would be appreciated, I'm going to continue to try and figure it out but if there is a way to do this simply then I'd love to hear and learn from it! Thank you.
public static String[] replacePairs(String []words, String [] beforeList, String [] afterList) {
if(words == null || beforeList == null || afterList == null){
return null;
}
String[] returnArray;
int countofSpaces = 0;
/* Check if words in words array can be found in beforeList, here I use
a method I created "inList". If a word is found the index of it in
beforeList will be returned, if a word is not found, -1 is returned.
If a word is found, I set the word in words to the afterList value */
for(int i = 0; i < words.length; i++){
int listCheck = inList(words[i], beforeList);
if(listCheck != -1){
words[i] = afterList[listCheck];
}
}
// This is where I check for spaces (or attempt to)
for(int j = 0; j < words.length; j++){
if(words[j].contains(" ")){
countofSpaces++;
}
}
// Here I return an array that is the length of words + the space count)
returnArray = new String[words.length + countofSpaces];
return returnArray;
}
Here's one of the many ways of doing it, assuming you have to handle cases where words contain more than 1 consecutive spaces:
for(int i = 0; i < words.length; i++){
int listCheck = inList(words[i], beforeList);
if(listCheck != -1){
words[i] = afterList[listCheck];
}
}
ArrayList<String> newWords = new ArrayList<String>();
for(int i = 0 ; i < words.length ; i++) {
String str = words[i];
if(str.contains(' ')){
while(str.contains(" ")) {
str = str.replace(" ", " ");
}
String[] subWord = str.split(" ");
newWords.addAll(Arrays.asList(subWord));
} else {
newWords.add(str);
}
}
return (String[])newWords.toArray();
This question already has an answer here:
Remove a common word from each string value in an array
(1 answer)
Closed 6 years ago.
I have an array of Strings that contains: Extra Water, Juice, and Extra Milk, so I am wondering how would I get rid of the extras and use the only second word in the string so that the expected output is Water, Juice, and Milk.
If all you want to do is remove a specific substring then:
String[] array = {"Extra Water", "Juice", "Extra Milk"};
array = Arrays.stream(array).map(s-> s.replaceAll("Extra", "")).toArray();
This uses Java 8 streams but you could do it just as simply with iteration.
Use String.split(' ') to split the string by a space, then check the result to see if the string length == 2. If so, then take the second element of the array, otherwise the first.
for( int i = 0; i < array.length; i++ ) {
String[] parts = array[i].split(' ');
if( parts.length == 2 ) {
array[i] = parts[1];
}
}
EDIT: If you want to remove all duplicate words, you could do the following using two passes over the array:
// Pass 1 -- find all duplicate words
Set<String> wordSet = new HashSet<>();
Set<String> duplicateSet = new HashSet<>();
for (int i = 0; i < array.length; i++) {
String[] parts = array[i].split(" ");
for (String part : parts) {
if (!wordSet.contains(part)) {
// Haven't seen this word before
wordSet.add(part);
} else {
// This word is a duplicate word
if (!duplicateSet.contains(part)) {
duplicateSet.add(part);
}
}
}
}
// Pass 2 -- remove all words that are in the duplicate set
for (int i = 0; i < array.length; i++) {
String[] parts = array[i].split(" ");
String dedupedString = "";
for (String part : parts) {
if (!duplicateSet.contains(part)) {
dedupedString += part + " ";
}
}
array[i] = dedupedString;
}
Simply you need to iterate over each element of the array and replace the "Extra" in each element of the array and then trim the white spaces.
String[] array = {"Extra Water", "Juice", "Extra Milk"};
for (int i = 0; i < array.length; i++) {
array[i] = array[i].replace("Extra", "").trim();
}
for (String each : array) {
System.out.println(each);
}
This question already has answers here:
how to compare two string arrays without java utils
(3 answers)
Closed 7 years ago.
I have to arrays of string
Array 1
Dog
Cat
Mouse
Chicken
Array 2
Cat
Dog
Mouse
Chicken
How can I check if the arrays comtains the same elements (order does not matter)
I guess I should first sort the array and than to compare
I am looking for a boolean answer
EDIT using Java utils is an option for me, I am just not familiar with JAVA enough
Just sort them both and iterate over the elements to compare them all:
public boolean compareStringArrays(String[] arr1, String[] arr2) {
if (arr1.length != arr2.length)
return false;
String[] arr1Copy = arr1.clone();
String[] arr2Copy = arr2.clone();
Arrays.sort(arr1Copy);
Arrays.sort(arr2Copy);
for (int i=0; i<arr1Copy.length; i++) {
if (!arr1Copy[i].equals(arr2Copy[i]))
return false;
}
return true;
}
Note that I make copies of the arrays here: this is so the original order of the arrays passed in is preserved. There's also an optimisation to check the lengths are the same first, as if one array has more elements than the other they are obviously not equal.
EDIT
you can also use Arrays.equals() instead of a for loop (which I originally didn't think of but seems obvious now), so you could achieve this with a one-liner:
Arrays.equals(Arrays.sort(arr1.clone()), Arrays.sort(arr2.clone()));
ArrayList<String> arrList1 = new ArrayList<>(Arrays.asList(arr1));
ArrayList<String> arrList2 = new ArrayList<>(Arrays.asList(arr2));
Collections.sort(arrList1);
Collections.sort(arrList2);
if (Arrays.equals(arrList1.toArray(), arrList2.toArray())) {
//They have exactly the same elements
}
EDIT:
Old answer:
ArrayList<String> arrList1 = new ArrayList<>(Arrays.asList(arr1));
ArrayList<String> arrList2 = new ArrayList<>(Arrays.asList(arr2));
if (arrList1.containsAll(arrList2) && arrList2.containsAll(arrList1)) {
//They have the same elements, not necessarily the same number
}
The top answer will tell you if they both contain the same elements, as well as if they have the same number, Bottom answer will tell you if they both have the same elements, but doesn't tell you if any elements are duplicated
EDIT again:
Firstly I posted:
if (arrList1.containsAll(arrList2) && arrList2.containsAll(arrList1)
&& arrList1.size() == arrList2.size())
Checking the size is equal is redundant, since if we have the lists:
Cat
Cat
Dog
and
Cat
Dog
Dog
The expression would evaluate to true, but they do not have exactly the same elements
Here is the method:
public boolean compareArray(){
boolean isSameArray=false;
String[] arr1={"Dog","Cat","Mouse","Chicken"};
String[] arr2={"Cat","Dog","Mouse","Chicken"};
Arrays.sort(arr1);
Arrays.sort(arr2);
if(Arrays.equals(arr1, arr2)){
isSameArray=true;
}else{
isSameArray=false;
}
return isSameArray;
}
That is very easy. Just do like this:
ArrayList<String> firstArray=new ArrayList<>();
ArrayList<String> secondArray=new ArrayList<>();
firstArray.add("Dog");
firstArray.add("Cat");
firstArray.add("Mouse");
firstArray.add("Chicken");
secondArray.add("Cat");
secondArray.add("Dog");
secondArray.add("Mouse");
secondArray.add("Chicken");
boolean areEqual=firstArray.containsAll(secondArray);
if(areEqual)
System.out.println("Voila!");
else
System.out.println("Oppps!");
May ways how to do that
- probably the best way is to make sort and compare Arrays like Collections(Arrays.sort(arrayToSort)), objects (Arrays.equals(arr1,arr2))
- another way is just iterate over 1st and 2nd array and try to find items one by one (bad idea, not such effective, but good to understand and explain)- something like following:
String[] arr1={"Dog","Cat","Mouse","Chicken"};
//String[] arr2={"Dog","Mouse","Chicken"}; //FALSE
String[] arr2={"Cat","Dog","Mouse","Chicken"}; //TRUE
boolean foundAll = true;
if(arr1.length != arr2.length){
foundAll = false;
}else{
for (int i = 0; i < arr1.length; i++) {
boolean foundActual = false;
for (int j = 0; j < arr2.length; j++) {
if(arr1[i].equals(arr2[j])){
foundActual = true;
break;
}
System.out.println("arr1 elem: " + arr1[i] + " arr2 elem: "+ arr2[j]);
}
System.out.println("\n");
if(!foundActual){
foundAll = false;
break;
}
}
}
System.out.println("found all: " + foundAll);
}
String arr1[] = {//your content goes here};
String arr2[] = {//your content goes here};
Arrays.sort(arr1);
Arrays.sort(arr2);
if(arr1.length != arr2.length){
retrn false;
}else{
boolean isSimilar = true;
for(int i=0; i< arr1.length; i++){
if(!(arr1[i].equals(arr2[i]))){
isSimilar = false;
}
}
}
return isSimilar;
I was trying to remove the duplicates from the list of arrays, I was trying to use simple for loop instead of hashset..
Can anyone suggest how can I improve my program:
public class removeduplicates {
public static void main(String[] args) {
String[] words={"Others","Others","Others","Sentence"};
String output=words[0];
int count=0;
for(int i=0;i<words.length-1;i++) {
for(int j=i+1;j<words.length;j++) {
if(words[i].equals(words[j])) {
count++;
}
else {
output=output+words[j];
}
}
i=count;
}
System.out.println(output);
}
}
In this program if we give input as Others, Sentence, Others, Sentence then I am not getting the required output: I need just Others and Sentence as output...
If possible I have a condition that when I am entering words array, I need the output array with only unique values in the same array words.
String [] input={"other", "other","sentence","other"};
String current=input[0];
boolean found=false;
for(int i=0; i<input.length; i++){
if (current == input[i] && !found) {
found = true;
} else if (current != input[i]) {
System.out.print(" " + current);
current = input[i];
found = false;
}
}
I suggest to use collections as you can't resize an array
ArrayList<String> noDuplicateList = new ArrayList<>();
String[] words={"Others","Others","Others","Sentence"};
for(int i=0;i<words.length;i++) {
if(!noDuplicateList.contains(words[i])){
noDuplicateList.add(words[i]);
}
}
Here's a link
The simplest way to solve the duplication is declared already using HashSet, Anyway look at this code using loop:
Step 1: replace duplicate value with null
String[] words={"Others","B","Sentence","A","Others","A","Sentence"};
for(int i=0; i < words.length ;i++) {
String toBeRemoved = words[i];
for(int j=i+1 ; j < words.length; j++) {
if(words[j] != null && words[j].equals(toBeRemoved)) {
words[i] = null;
}
}
}
Now if you print the words values then the output will be:
System.out.println(Arrays.asList(words));
output: [null, B, null, null, Others, A, Sentence]
Step 2: Remove the null values (there are many ways to do it) for example:
List<String> list = new ArrayList<>(Arrays.asList(words));
list.removeIf(new Predicate<String>() {
#Override
public boolean test(String t) {
return (t == null || t.length() < 0);
}
});
words = list.toArray(new String[0]);
Using lambda JDK 8:
words = Arrays.stream(words).filter(t -> (t != null && t.length() > 0)).toArray(String[]::new);
Now if you print the words values then the output will be:
System.out.println(Arrays.asList(words));
output: [B, Others, A, Sentence]
This question already has answers here:
Java: Checking equality of arrays (order doesn't matter)
(10 answers)
Closed 9 years ago.
To compare two strings in java I used following code
String ary[]={"man","john","su"};
String ary1[]={"john","man","su"};
if(Arrays.equals(ary,ary1)) {
System.out.println("equal");
} else {
System.out.println("not equal");
}
It prints "not equal",But this two arrays are having same values.
Indeed here the both arrays are same but values positions change.
How can I tell that this kind of arrays are same.
Try this it will work.
String ary[]={"man","john","su"};
String ary1[]={"john","man","su"};
boolean isEqual = true;
if(ary.length != ary1.length) {
System.out.println("not equal");
} else {
int countEquals = 0;
ArrayList<String> wordList = new ArrayList(Arrays.asList(ary1) );
for (String str : ary) {
if (wordList.contains(str)) {
countEquals++;
wordList.remove(str);
} else {
isEqual = false;
System.out.println("not equal");
break;
}
}
if (isEqual) {
System.out.println("equal");
}
}
From what I see you just try to see if they are equal, if this is true, just go with something like this:
boolean areEqual = Arrays.equals(Arrays.sort(arr1), Arrays.sort(arr2));
This is the standard way of doing it.
Doing so because like ZouZou states and as marked in the documentation:
"Two arrays are considered equal if both arrays contain the same
number of elements, and all corresponding pairs of elements in the two
arrays are equal. In other words, two arrays are equal if they contain
the same elements in the same order"
Use Sets:
if (ary.length == ary1.length && new HashSet<>(Arrays.asList(ary)).equals(new HashSet<>(Arrays.asList(ary1)))
Test code:
String ary[] = { "man", "john", "su" };
String ary1[] = { "john", "man", "su" };
Set<String> set1 = new HashSet<>(Arrays.asList(ary));
Set<String> set2 = new HashSet<>(Arrays.asList(ary1));
System.out.println(ary.length == ary1.length && set1.equals(set2));
Output:
true
String ary[] = { "man", "john", "su" };
String ary1[] = { "man", "john", "su" };
boolean check = true;
for(int i=0; i<ary.length; i++)
{
for(int j=0; j<ary1.length; j++)
{
if(i == j)
{
if(!ary[i].equals(ary1[j]))
{
check = false;
}
}
}
}
This code may be help you. Good Luck.