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;
Related
This question already has answers here:
Simple way to find if two different lists contain exactly the same elements?
(20 answers)
Closed 11 months ago.
I need to check if the elements in the arraylist are arranged in ascending order or not. and when i use this code, the output shows "not sorted" even for a sorted array. why is it showing the wrong output?**
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> array1 = new ArrayList<>();
ArrayList<Integer> array2 = new ArrayList<>();
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
array1.add(i, sc.nextInt());
array2.add(i, array1.get(i));
}
Collections.sort(array1);
if (array1 == array2) {
System.out.println("sorted");
}
else {
System.out.println("not sorted");
}
}
"==" checks weather two object identical that means it check weather they point to the same memory location. If your array1 is on #698 location your array2 will be somewhere else like #700 ,so they don't point to the same location that's why it shows they are not equal. You better check it on this way:
if (array1.equals(array2)){
System.out.println("They are equal");
} else{
System.out.println("They are not equal");
Then it shows the right answer
The error using == instead of equals is clear. For arrays there is Arrays.equals(int[] lhs, int[] rhs).
However sort does too much work, and needs a copy of the array.
Better:
static boolean isSorted(List<Integer> list) {
for (int i = 1; i < list.size(); ++i) {
if (list.get(i).compareTo(list.get(i - 1)) < 0) {
return false;
}
}
return true;
}
Could even be more general:
static <T extends Comparable<T>> boolean isSorted(List<T> list) {
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.
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;
}
I have 2 parallel arrays: the first contains State Names, the second Capitals of the states.
I'm making a quiz that randomly generates a State then asks the user to enter the Capital of the state. Once the input is received I want to call a method to check if the index of the capital entered is the same as the index of the state it goes with.
ie: stateArray[0] = "New York" and capitalArray[0] = "Albany".
Check Answer Method
public static void checkAnswer(String[]stateArray, String capitalArray, String answer)
{
int index;
for (int i = 0; i < capitalArray.length; i++){
if(capitalArray[i].equalsIgnoreCase(answer)){
index = i;
}
}
if(capitalArray[index] == stateArray[index])
{
System.out.println("correct");
}
else
{
System.out.println("incorrect");
}
}
I know the second if statement is wrong. How can I compare the two arrays using the index where the users answer was found in the capitalArray?
boolean checkAnswer(String[] stateArray, String[] capitalArray, String displayedState, String answer) {
for (int i = 0; i < stateArray.length; i++) {
if (stateArray[i].equals(displayedState) && capitalArray[i].equals(answer)) {
return true;
}
}
return false;
}
Or something. The key is you need to pass in something to represent the state you displayed.
You need to keep track of the index that holds the State displayed to the user. For example, the way your code is written now gives the user the ability to get a right answer by giving a wrong answer. Take this example as explanation:
string[] stateArray = {"New York", "California"};
string[] capitalArray = {"Albany", "Sacramento"};
If you were to show "New York" as the question and the user happens to answer "Sacramento" your code would display correct.
You also need a case in which the answer does not match any of the capitals in the array. One way of doing this to implement in your code is to initiate the index to -1.
int index = -1;
Once you finish the for loop check if index is -1 and display "Your answers is not a valid State" or something along those lines.
Maybe use a HashMap, I am not completely familiar with Java it appears to be the similar to a Dictionary in Python. Dictionary object has great performance.
Since you know what state you asked about you should know its array index as well. As you see below both arrays are declared as class variables.
... class Quiz {
private String[] states = new String[50];
private String[] capitals = new String[50];
... method to fill both arrays with the correct data
public static void checkAnswer(int question, String answer)
{
if(capitalArray[question].equalsIgnoreCase(answer)){
{
System.out.println("correct");
}
else
{
System.out.println("incorrect");
}
}
}
It's better to have checkAnswer method's return type as Boolean, but I left it your way.
An alternate implementation in Java would be to use a Map instead of two arrays.
Map<String,String> stateCapitals = new HashMap<String,String>();
stateCaptitals.put("New York", "Albany");
then you can check the map with
public voic checkAnswer(String chosenState, String chosenCapital) {
if (stateCapitals.get(chosenState).equals(chosenCapital) {
System.out.println("you are correct!");
}
}
This does not do it with 2 parallel arrays, but it is a better implementation if your real concern is the type of data you mentioned, and not the arrays themselves.
Try this function it return array:-
public static String[] numSame (String[] list1, String[] list2)
{
int same = 0;
for (int i = 0; i <= list1.length-1; i++)
{
for(int j = 0; j <= list2.length-1; j++)
{
if (list1[i].equals(list2[j]))
{
same++;
break;
}
}
}
String [] array=new String[same];
int p=0;
for (int i = 0; i <= list1.length-1; i++)
{
for(int j = 0; j <= list2.length-1; j++)
{
if (list1[i].equals(list2[j]))
{
array[p]= list1[i]+"";
System.out.println("array[p] => "+array[p]);
p++;
break;
}
}
}
return array;
}
Let's say I got this array:
String[][]array = new String[5][5];
array[2][2] = desperate;
Would it be possible to find whether
String s = "desperate"; - equals any array element without using a for loop, and without having to manually enter the row column combination of the array assigned the value "desperate"?
while loop instead of for loop
int i = 0;
int j = 0;
while (i < n)
{
while (j < m)
{
if (array[i][j].equals("..."))
{
///
}
j++;
}
i++;
}
Use enhanced-for loop: -
String [][] array = new String[2][2];
array[1][1] = "desperate";
array[0][1] = "despee";
array[1][0] = "despete";
array[0][0] = "dete";
for (String[] innerArr: array) {
for (String value: innerArr) {
if (value.equals("desperate")) {
System.out.println(value + " == desperate");
}
}
}
Output: - desperate == desperate
A better way that I would suggest is to use ArrayList<String> to store your items.. Then you can just call contains() method to check whether the list contains that element..
List<String> listString = new ArrayList<String>();
listString.add("desperate");
listString.add("despe");
if (listString.contains("desperate")) {
System.out.println("True");
}
Output: - True
Assuming that you can't (for any reasons) change your array to another collection type:
String[][]array = new String[5][5];
array[2][2] = "desperate";
public boolean contains(String str){
return new HashSet<String>((List<String>)Arrays.asList(array)).contains(str);
}
Better than transforming it to a List since HashSet's contains() method is O(1) and the one from List is O(n).
The only way to avoid using a loop (and it not clear why you would want to) is to use a Map which you pre-build with all the strings and indexes.