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.
Related
I currently have a String Array
String[] properSequence = ability.getSequence();
And I want to compare it to an ArrayList
ArrayList<String> sequence
As of right now I'm doing,
boolean matchesSequence = true;
String[] properSequence = ability.getSequence();
int index = 0;
for(String s : sequence) {
String s1 = properSequence[index];
if(!s1.equalsIgnoreCase(s)) {
matchesSequence = false;
break;
}
index++;
}
if(matchesSequence) {
// Matches, code
}
I was wondering if there's an easier/prettier way of doing this, seems a bit redundant.
Your code may throw ArrayIndexOutOfBoundsException. Check the bounds of array as well as the list as shown below:
for(int i = 0; i < Math.min(sequence.size(), properSequence.length); i++) {
if(!sequence.get(i).equalsIgnoreCase(properSequence[i])) {
matchesSequence = false;
break;
}
}
Alternatively,
for(int i = 0; i < sequence.size() && i < properSequence.length; i++) {
if(!sequence.get(i).equalsIgnoreCase(properSequence[i])) {
matchesSequence = false;
break;
}
}
You can use built-in equals method:
if(!Arrays.equals(sequence.toArray(),properSequence))
matchesSequence = false;
You could convert the String[] into an ArrayList and compare those two, but you can't do that if you want equalsIgnoreCase() in the comparison. However, if you put all the elements in the String[] and the ArrayList in upper (or lower) case, you could do this:
if (Arrays.asList(properSequence).equals(sequence))
{
...
}
Arrays and Lists are only considered equal to each other if the elements are equal and in the same order.
To compare an Array of object to a List of the same object you can do the following using the Arrays#compare method. Different versions have different capabilities. This example uses Strings and does a case insensitive compare. It also makes use of List.toArray introduced in JDK 11
List<String> list = List.of("A", "B", "C");
String[] array1 = { "a", "b", "c" };
String[] array2 = { "a", "c", "b" };
for (String[] array : new String[][] { array1, array2 }) {
if (Arrays.compare(array, list.toArray(String[]::new),
String.CASE_INSENSITIVE_ORDER) == 0) {
System.out.printf("%s equals %s%n",
Arrays.toString(array), list);
} else {
System.out.printf("%s does not equal %s%n",
Arrays.toString(array), list);
}
}
Prints
[a, b, c] equals [A, B, C]
[a, c, b] does not equal [A, B, C]
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.
How to check if String contains all Strings from Array.
My current code:
String word = "abc";
String[] keywords = {"a", "d"};
for(int i = 0; i < keywords.length; i++){
if(word.contains(keywords[i])){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
The code would look much more nicer if you wrap it into a separate method:
public static boolean containsAllWords(String word, String ...keywords) {
for (String k : keywords)
if (!word.contains(k)) return false;
return true;
}
If you are using Java 8+, you could use a Stream and test if all of the elements match your criteria with one line. Like,
if (Stream.of(keywords).allMatch(word::contains)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
In earlier versions, or if you want to understand what the above is doing, it might look something like
boolean allMatch = true;
for (String kw : keywords) { // <-- for each kw in keywords
if (!word.contains(kw)) { // <-- if "word" doesn't contain kw
allMatch = false; // <-- set allMatch to false
break; // <-- stop checking
}
}
if (allMatch) {
System.out.println("Yes");
} else {
System.out.println("No");
}
Use a boolean variable that will tell you if every keyword is matched. Set it to true as default value. Then check every keword: if any one is not contained in your word, stop searching and set your variable to false.
boolean containsAll = true;
for (String keyword : keywords){
if (!word.contains(keyword)){
containsAll = false;
break;
}
}
Note this solution work only if your keywords contain one char, there are many answers already mentioned if your keywords contain more then one char.
With one line :
boolean contain = Arrays.asList(word.split("")).containsAll(Arrays.asList(keywords));
The idea is :
String word = "abc";
String[] split = word.split("");
Split your String to get an array of chars split = {a, b, c}
String[] keywords = {"a", "b"};
Check if your array1 contain all the element of the second array2 using containsAll
boolean contain = Arrays.asList(split).containsAll(Arrays.asList(keywords));
Either use StringUtils (org.apache.commons.lang.StringUtils). It will return the index of the first occurrence of keywords or -1 if it is not there.
StringUtils.indexOfAny(word, keywords);
Or you can use Arrays which will return the boolean value.
Arrays.asList(word).contains(keywords)
A better code would be:
for(String s: keywords){
if(word.contains(s)){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
Simply use a counter:
String word = "abc";
String[] keywords = {"a", "d"};
int counter = 0;
for(int i = 0; i < keywords.length; i++){
if(word.contains(keywords[i])){
counter++;
}
}
if(counter == keywords.length){
System.out.println("Yes");
}else{
System.out.println("No");
}
If the counter equals the keywords length, it means that all elements are contained. With this solution you will also be able to find out how many keywords are matched by the word.
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'm looking for a method to detect if all objects within an array(list) are the same.
e. g:
arraylist1 = {"1", "1", "1", "1"} // elements are the same
arraylist2 = {"1", "1", "0", "1"} // elements are not the same
Thanks for help
Java 8 solution :
boolean match = Arrays.stream(arr).allMatch(s -> s.equals(arr[0]));
Same logic for lists :
boolean match = list.stream().allMatch(s -> s.equals(list.get(0)));
It comes quite complicated if there are only or any null values in the array (resulting in a NullPointerException). So possible workarounds are:
Using Predicate.isEqual, it uses the static method equals from the Objects class and it will do the null check for you before calling equals on the first argument.
boolean match = Arrays.stream(arr).allMatch(Predicate.isEqual(arr[0]));
boolean match = Arrays.stream(arr).allMatch(s -> Objects.equals(arr[0], s));
Using distinct() and count() :
boolean match = Arrays.stream(arr).distinct().count() == 1;
that can be improved into Arrays.stream(arr).distinct().limit(2).count() == 1; as there is no need to check the all pipeline's content if you already find 2 distinct elements.
public static boolean AreAllSame(String[] array)
{
boolean isFirstElementNull = array[0] == null;
for(int i = 1; i < array.length; i++)
{
if(isFirstElementNull)
if(array[i] != null) return false;
else
if(!array[0].equals(array[i])) return false;
}
return true;
}
Please feel free to correct any syntax mistakes. I fear my Java-fu may be lacking today.
if( new HashSet<String>(Arrays.asList(yourArray)).size() == 1 ){
// All the elements are the same
}
If your list is empty return true.
If not, loop through it and check if all elements are equal to the element at index 0.
If so, return true, otherwise return false.
public boolean containsSameValues(int[] array) {
if(array.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
int first = array[0];
for(int i=0;i<array.length;i++) {
if(array[i] != first) {
return false;
}
}
return true;
}
boolean containsAllValues=false;
boolean t=false;
int isto=0;
for(int k=0;k<arraylist1.size();k++){
for(int n=0;n<arraylist2.size();n++){
if(arraylist1.get(k).equals(arraylist2.get(n))){
t=true;
}
}
if(t){
isto++;
}else{
isto=0;
break;
}
}
if(isto!=0){
containsAllValues=true;
}
With this you can check if arraylist2 contains values from arraylist1.
You can sort the array and then use the Array equals method:
public boolean equalArrays(int []f ,int [] g){
Arrays.sort(f);
Arrays.sort(g);
if (Arrays.equals(f, g))
return true;
return false;
}
To test it out:
int [] h={1,1,0,1};
int [] t={1,1,1,0};
System.out.println(cc.equalArrays(h,t));
For Java 8, Alexis C's solution is probably the best. However, if you're stuck with <= Java 7 and don't think David Wallace's approach is expressive enough, you could also try this:
boolean result = Collections.frequency(yourList, "1") == yourList.size();
Basically what this does is that it checks whether the number of elements in your list equal to "1" matches the total number of elements in the list. Pretty straightforward.
By the way -- this is pure Java Collections API, and I believe Collection.frequency(..) has been there since at least JDK 1.5. See the javadocs for more information.
EDIT: Here's a quick fiddle if you want to take this for a test drive.
The easiest one:
public static boolean checkTheSame(int[] numbers) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] != numbers[i + 1]) {
return false;
}
}
return true;
}