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]
Related
How can i compare two different size arraylists and check the order of elements?
1.First check is ArrayList1 is subset of list2
2.Second check is ArrayList2 has same order as List1, ignoring random elements
Arraylist1{"this", "is", "a", "coding", "test"};
Arraylist2{"this", "is", "random1", "a", "random2", "coding", "random3", "test"};
The test will pass if List2 is in this order:
"this" "is" "a" "coding" "test"
The test will fail if List 2 has any other order like:
"a", "is", "coding", "test", "this", or if any of these 5 words are missing.
The program should ignore any number of randoms values (like random1, random2, and random3) in List 2.
How can I achieve this scenario?
I tried for loops and iterators. It didn't work, they gave me common elements of both ArrayList but not the "order". What else can I do?
for loop using:
list1.contains(list2.get(i)))
But this is comparing only values and doesn't check for order.
Iterator with while loop:
Iterator<String> List1_Iterator = List1.iterator();
while (List1_Iterator.hasNext()) {
}
This also doesn't check for order of elements.
You can also do this simple process as per your steps.
1) compare the elements.
2) compare the order.
import java.util.*;
class Stack1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();
list.add("First");
list.add("name");
list.add("is");
list.add("Jay");
ArrayList<String> list2=new ArrayList<String>();
list2.add("First");
list2.add("name");
list2.add("is");
list2.add("Sudeep");
ArrayList<String> list3=new ArrayList<String>();
for(int i=0;i<list2.size();i++)
{
for(int j=0;j<list.size();j++)
{
if(list2.contains(list.get(j))==true)
{
if(list2.get(i)==list.get(j))
{
list3.add(list2.get(i));
}
}
else{ break; }
}
}
if(list.equals(list3))
{
System.out.println("true");
}
else{System.out.println("false");}
}
}
One way to do this is to first create a copy of list 2 called list2Copy, then remove all the elements in list2Copy that does not exist in list1. Now you just need to compare if they are exactly equal to each other.
List<Integer> list1 = Arrays.asList(1,3,5);
List<Integer> list2 = Arrays.asList(1,2,3,4,5);
ArrayList<Integer> list2Copy = new ArrayList<>(list2);
list2Copy.removeIf(x -> !list1.contains(x));
return list1.equals(list2Copy);
Here's another approach with a smaller time complexity:
if (list1.size() > list2.size()) {
// definitely not same order
return false;
}
int list1Index = 0;
for (int i = 0 ; i < list2.size() ; i++) {
if (Objects.equals(list2.get(i), list1.get(list1Index))) {
list1Index++;
if (list1Index == list1.size()) {
return true;
}
}
}
// at the end, list1Index should be the same as list1.size() if list2 is in the same order.
return false;
You start with the first element of the first list and you try to find it in the second list. If/When you find it, you assign the index of the element in list 2 to a local variable (indexList2). Then you go to the second element of the first list and try to find it in list 2 but you don't start at index 0 but at the indexList2. You keep on going until you've looped over all the element in list 1 (and found them in list 20 --> test is successful, otherwise, test is a failure
Arraylist is indexed so, you can loop over the smallest list and then check for the mismatch by comparing the value at the indices. A method which does the same- will return true only if the elements are in correct order in both the lists ( one list is a subset of the other and the elements are equal in the same order), in a efficient way.
private boolean checkForEqualityInorder(List<String> list1, List<String> list2) {
if (list1.size() < list2.size()) {
for (int i=0; i <list1.size(); i++){
if( !list1.get(i).equals(list2.get(i))) {
return false;
}
}
} else {
for (int i=0; i <list2.size(); i++){
if( !list2.get(i).equals(list1.get(i))) {
return false;
}
}
}
return true;
}
The above method accepts two lists, and will return true only if one is subset of the other (checked in order).
Enhancing the same method for your problem:
private boolean checkForEqualityInorder(List<String> list1, List<String> list2) {
for (int i=0, k=0; i <list1.size(); i++, k++){
if (list2.get(k).startsWith("random")) {
i--;
continue;
}
if(!list1.get(i).equals(list2.get(k))) {
return false;
}
}
return true;
}
public static final BiPredicate<List<String>, List<String>> isHasSameOrder = (one, two) -> {
Iterator<String> it1 = one.iterator();
Iterator<String> it2 = two.iterator();
nextWord:
while (it1.hasNext()) {
String word = it1.next();
while (it2.hasNext())
if (word.equals(it2.next()))
continue nextWord;
return false;
}
return true;
};
Demo
List<String> one = Arrays.asList("this", "is", "a", "coding", "test");
List<String> two = Arrays.asList("this", "is", "random1", "a", "random2", "coding", "random3", "test");
System.out.println("same order: " + isHasSameOrder.test(one, two)); // true
This question already has answers here:
Create ArrayList from array
(42 answers)
Closed 6 years ago.
I would like to convert an Array of Strings into an ArrayList of ArrayList, where the inner ArrayList has a dynamic number of elements. Who can help ? Thanks in advance
String[] sentences = {"hello","how are you","i am fine","and you ?","thank you"}
//Output with number of elements = 2
["hello","how are you"]
["i am fine","and you ?"]
["thank you"]
//Output with number of elements = 3
["hello","how are you","i am fine"]
["and you ?","thank you"]
public static void main(String[] args) {
String[] sentences = {"hello", "how are you", "i am fine", "and you ?", "thank you"};
System.out.println(split(2,sentences));
System.out.println(split(3,sentences));
}
public static List<List<String>> split(int numberOfElements, String[] sentences) {
List<List<String>> lists = new ArrayList<List<String>>();
int index = 0;
for (String sentence : sentences) {
if (index % numberOfElements == 0) {
lists.add(new ArrayList<String>());
}
lists.get(index / numberOfElements).add(sentences[index]);
index++;
}
return lists;
}
Output:
[[hello, how are you], [i am fine, and you ?], [thank you]]
[[hello, how are you, i am fine], [and you ?, thank you]]
public static void main(String[] args) {
String[] sentences = { "hello", "how are you", "i am fine", "and you ?", "thank you" };
List<List<String>> convertIntoList = convertIntoList(sentences, 2);
System.out.println(convertIntoList);
convertIntoList = convertIntoList(sentences, 3);
System.out.println(convertIntoList);
}
private static List<List<String>> convertIntoList(String[] sentences, int nbElement) {
List<List<String>> listOfListTarget = new ArrayList<List<String>>();
int currentIndex = 0;
while (currentIndex < sentences.length) {
int nextIndex = currentIndex + nbElement;
if (nextIndex > sentences.length) {
nextIndex = sentences.length;
}
final String[] copyOfRange = Arrays.copyOfRange(sentences, currentIndex, nextIndex);
List<String> subList = new ArrayList<String>();
subList.addAll(Arrays.asList(copyOfRange));
listOfListTarget.add(subList);
currentIndex+=nbElement;
}
return listOfListTarget;
}
Is this is a homework?
So you have an array of strings, and you want to create a List> with that, with each inner List containing at most x number of elements.
To get x number of elements and put them in a List, you can do a simple for loop.
String[] myStringArray = { ... };
List<String> myListOfString = new ArrayList<>();
for(int i=0; i<x; i++) {
myListOfString.add(myStringArray[i]);
}
So for example if you have these values
String[] myStringArray = {"a", "b", "c", "d", "e"};
x = 2;
You'll get the following list using the above loop:
["a", "b"]
Great! But we need to get all the contents of the myStringArray! How do we do that? Then let's do the first step, we iterate through all the contents of the array. We can do that like this.
int i=0;
while(i < myStringArray.length) {
System.out.println(myStringArray[i]);
i++;
}
Which will output:
a
b
c
d
e
This doesn't solve the problem... but at least we know how to iterate the whole thing. The next step is to get x of them. Sounds simple right? So basically we need to create a list of x from the contents. Maybe we can use the logic we created a few examples back to solve the problem.
// Create list of list of string here
int i = 0;
while(i < myStringArray.length) {
// Create list of string here
for(int j=0; j<x; j++) {
// Add myStringArray[j] to list of string here
}
// Add the list of string to the list of list of string here
i++;
}
Easy right? No. This gives the following lists:
["a", "b"]
["a", "b"]
["a", "b"]
["a", "b"]
["a", "b"]
Why? In the first loop, we are iterating up to how many is in the array. In the second loop, we are adding element 0 and 1 to a list. Obviously it wouldn't work. The second loop needs to be aware that it should not add previously added elements, and at the same time the first loop needs to be aware of what the second loop is doing. So you might think, maybe we can use the int i to indicate where the second loop should start?
int i = 0;
while(i<myStringArray.length) {
while(i<x) {
// add myStringArray[i];
i++;
}
i++;
}
Unfortunately, using the same values as previous, this will only give the following list
["a", "b"]
Because i is iterating through the whole array. So when it goes from 0 to length, whatever the value of i is used on the second array. When it loops again, i becomes 1, so the start of the second loop is at 1.
We need a separate variable to do the counting, while still keeping in mind where we currently are in the second loop.
int i = 0;
while(i<myStringArray.length) {
int count = 0;
while(count < x) {
// Add myStringArray[count+i] to list of string
count++;
}
// Add to list of list of string
i += count + 1; // Need to be aware of how much we have processed
}
This will do what we want, but unfortunately we can get in trouble at certain values. Say x is 10 and myStringArray is only of length 2. This will throw an exception because when it reaches the point of count+i = 3, that index doesn't exist anymore. The second loop also needs to be aware of how much is still remaining.
Finally we'll have the following code
int i = 0;
while(i<myStringArray.length) {
int count = 0;
while(count < x && count+i < myStringArray.length) {
// Add myStringArray[count+i] to list of string
}
// Add to list of list of string
i += count; // Need to be aware of how much we have processed
}
Which will give
["a", "b"]
["c", "d"]
["e"]
Edit: Next time try to put some code that you tried something.
How to check if the two arrays have same values, ignoring their position. The arrays can have multiple of same value.
Example 1
String[] a = {"m","o","m","d","a","d"};
String[] b = {"d","a","d","m","o","m"};
//This should result true.
Example 2
String[] a = {"m","o","m","d","a","d"};
String[] b = {"d","a","d","m","o"};
//This should result false because second array has only one m and first array has two
I hope my condition is understood by example.
I am trying to check if the words are anagrams. I have made array out of words. But could not check if the arrays have same values. My code is as follows:
public class AreAnagrams {
public static boolean areAnagrams(String a, String b) {
//throw new UnsupportedOperationException("Waiting to be implemented.");
if(a.length() != b.length()) return false;
String[] test = new String[a.length()];
String[] testb = new String[b.length()];
for(int i=0; i<a.length(); i++){
test[i] = a.substring(i,i+1);
testb[i] = b.substring(i,i+1);
}
return test.equals(testb);
}
public static void main(String[] args) {
System.out.println(areAnagrams("momdad", "dadmom"));
}
}
You can sort the two arrays with Arrays.sort() and then compare the sorted arrays with Arrays.equals() to find out if they have the same values.
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.
In this part of code:
System.out.println("Alunos aprovados:");
String[] aprovados = {"d", "a", "c", "b"};
List<String> list = new ArrayList();
for (int i = 0; i < aprovados.length; i++) {
if (aprovados[i] != null) {
list.add(aprovados[i]);
}
}
aprovados = list.toArray(new String[list.size()]);
Arrays.sort(aprovados);
System.out.println(Arrays.asList(aprovados));
An example result of System.out.println is:
[a, b, c, d]
How could I modify the code above if I want a result like below?
a
b
c
d
Or, at least:
a,
b,
c,
d
Iterate through the elements, printing each one individually.
for (String element : list) {
System.out.println(element);
}
Alternatively, Java 8 syntax offers a nice shorthand to do the same thing with a method reference
list.forEach(System.out::println);
or a lambda
list.forEach(t -> System.out.println(t));
If one wants to display each element in the same line, without those brackets:
public static void main(String[] args) {
Set<String> stringSet = new LinkedHashSet<>();
stringSet.add("1");
stringSet.add("2");
stringSet.add("3");
stringSet.add("4");
stringSet.add("5");
int i = 0;
for (String value : stringSet) {
if (i < stringSet.size()-1) {
System.out.print(value + ",");
} else {
System.out.print(value);
}
i++;
}
}