I have two String Lists just like below:
List1 (Generated by sql resultset)
10001
10100
10001
List2 (Generated by sql resultset)
10000
10000
10000
Button Action;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
createList1();
createList2();
difference();
} catch (Exception ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
difference void;
public void difference (){
int minLen = Math.min(List1.get(0).length(), List2.get(0).length());
for (int i = -1 ; i != minLen ; i++) {
char chA = List1.get(0).charAt(i);
char chB = List2.get(0).charAt(i);
if (chA != chB) {
System.out.println(chA);
}
}
}
I want to find which index numbers are different in List1 for index 0.
Thanks in advance.
Make a loop that iterates the index i from zero the length of the shorter of the two strings, and compare characters one by one, using the == operator:
int minLen = Math.min(a.length(), b.length());
for (int i = 0 ; i != minLen ; i++) {
char chA = a.charAt(i);
char chB = b.charAt(i);
if (chA != chB) {
...
}
}
Before starting the comparison you need to check that a and b are not null. Otherwise, getting the length is going to trigger a null reference exception.
Try this:
public List<Integer> findDiffIndexes(String s1, String s2 ) {
List<Integer> indexes = new ArrayList<Integer>();
for( int i = 0; i < s1.length() && i < s2.length(); i++ ) {
if( s1.charAt(i) != s2.charAt(i) ) {
indexes.add( i );
}
}
return indexes;
}
https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringUtils.html#difference%28java.lang.String,%20java.lang.String%29
public static String difference(String str1,
String str2)
Compares two Strings, and returns the portion where they differ. (More precisely, return the remainder of the second String, starting
from where it's different from the first.)
For example, difference("i am a machine", "i am a robot") -> "robot".
StringUtils.difference(null, null) = null
StringUtils.difference("", "") = ""
StringUtils.difference("", "abc") = "abc"
StringUtils.difference("abc", "") = ""
StringUtils.difference("abc", "abc") = ""
StringUtils.difference("ab", "abxyz") = "xyz"
StringUtils.difference("abcde", "abxyz") = "xyz"
StringUtils.difference("abcde", "xyz") = "xyz"
Parameters:
str1 - the first String, may be null
str2 - the second String, may be null
Returns:
the portion of str2 where it differs from str1; returns the empty String if they are equal
Since:
2.0
Do loop on List 1 and List2, and compare index value like,
I assume you that both list has same size so,
for(int i=0;i<list1.size();i++)
{
if(!list1.get(i).equals(list2.get(i))
{
System.out.println("Not equal value of Index="+i);
}
}
Assuming the two Strings will always be the same length...
String first = "10000";
String second = "10101";
ArrayList differentIndexes = new ArrayList();
for(int i=0; i<first.length(); i++){
if(first.charAt(i)!=second.charAt(i)){
differentIndexes.add(i);
}
}
Related
String arr[]={"",""};
if(arr!=null && arr.length >0){
// the condition is becoming true
}
I need to check for empty values and return false
An empty string is still a value. The array has 2 'slots' available, therefore, its length is '2'.
You can query the individual objects in these slots, for example with: for (String elem : arr) { if (elem.isEmpty()) ..... ; }
You can stream the array, filter out elements that are not empty strings and get the count. Like,
boolean b = Arrays.stream(arr).filter(x -> !x.isEmpty()).count() != 0;
That will be false if the array is "empty" (and true otherwise).
String arr[] = ["", ""];
if(arr!=null && Array.length>0){
for (int i = 0; i < arr.length; i++) {
if(arr[i]==""){
return false;
break;
}
}
}
String arr[]={"",""};
int flag = 0;
for (int i=0; i<arr.length; i++){
if(arr[i]!="") {
flag = 1;
break;
}
}
if(flag==0){
//your code
}
I'm having a problem getting the unique letters and digits out of an array of strings, and then returning them. I am having a formatting issue.
The given input is: ([abc, 123, efg]) and is supposed to return abcefg123,
however, mine returns: abc123efg
how can I fix this since arrays.sort() will end up putting the numbers first and not last?
Here is my method so far:
public static String getUniqueCharsAndDigits(String[] arr) {
String str = String.join(",", arr);
String myString = "";
myString = str.replaceAll("[^a-zA-Z0-9]", "");
for(int i = 0; i < str.length(); i++) {
if(Character.isLetterOrDigit((i))){
if(myString.indexOf(str.charAt(i)) == -1) {
myString = myString + str.charAt(i);
}
}
}
return myString;
}
What you want to do is create two strings, one with the letters, one with the digits.
public static String getUniqueCharsAndDigits(String[] arr) {
String str = String.join("", arr);
String myLetters, myDigits;
myLetters = myDigits = "";
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(Character.isLetter(c)){
if(myLetters.indexOf(c) == -1) {
myLetters += c;
}
} else if(Character.isDigit(c)){
if(myDigits.indexOf(c) == -1) {
myDigits += c;
}
}
}
//if they need to be sorted, sort each one individually here
return myLetters + myDigits;
}
I've modified your code and deleted the unnecessary parts of it.
So, I want to compare from string to array of strings
String [] string = new String [10];
string [1] = "pencil";
string [2] = "pen";
string [3] = "eraser";
how do i compare string to the array of strings from above?
A quicker way is to use this code
if(Arrays.asList(string).contains(search_string))
If I understand you correctly, Write a loop, where iterate multiple string(example array) and equals with src string.
String [] string = new String [10];
...
String src = ..;//src string
for(String string : string){
if(src.equals(string)){
//Equal
}
}
Try using this:
for (int i = 0; i < string.length; i++) {
if (ch.equals(string[i])) { // ch is the string to compare
System.out.println("equal");//or whatever your action is
}
}
EDIT:
If what you are seeking to do is to verify if the searched string appears in the string[i] you can try:
string[0] = "pentagon";
string[1] = "pencil";
string[2] = "pen";
string[3] = "eraser";
string[4] = "penny";
string[5] = "pen";
string[6] = "penguin";
string[7] = "charp";
string[8] = "charpen";
string[9] = "";
String ch = "pen";
Then test if the arrays elements contain the searched string:
for (int i = 0; i < string.length; i++) {
if (string[i].indexOf(ch) != -1) {
System.out.println(string[i]+" contains "+ch);
} else
System.out.println(string[i]+" doesn't contain "+ch);
}
EDIT 2:
int i=0;
Boolean found=false;
while(i < string.length && !found) {
if (string[i].indexOf(ch) != -1) {
found=true;
}
i++;
}
if(found){
system.out.println(ch+" is found");
}
How do I compare 2 numbers which can have the values 202.10.200 and 202.101.30 in java. I understand the above 2 cannot be "numbers". We need to compare this keeping in mind 202.101.30 should be greater than 202.10.200.
Scanner keyboard = new Scanner(System.in);
String inputLine = keyboard.nextLine();
String[] inputArray = inputLine.split(".");
int[] numArray = null;
for(int i = 0; i < inputArray<length; i++)
{ numArray[i] = Integer.parseInt(inputArray[i]);
}
Then you just need to write another loop to compare another two input arrays with different numbers.
If you are sure that strings are syntattically identical and have the same number of elements separated by ".", you can split them into arrays, convert arrays elements into int and then compare them onw by one:
String s1 = "202.10.200";
String s2 = "202.101.30";
String sGreater = s1;
String[] strArr1 = s1.split("\\.");
String[] strArr2 = s2.split("\\.");
for (int i=0; i<strArr1.length; i++)
{
int x1 = Integer.parseInt(strArr1[i]);
int x2 = Integer.parseInt(strArr2[i]);
if (x2>x1)
{
sGreater = s2;
break;
}
}
This method can be used as an implementation of a Comparator:
public static int compareTo(String s1, String s2) {
String[] a1 = s1.split("\\.");
String[] a2 = s2.split("\\.");
for (int i = 0; i < 3; i++) {
if (!a1[i].equals(a2[i]))
return Integer.parseInt(a1[i]) - Integer.parseInt(a2[i]);
}
return 0;
}
This one works with any (but equal) number of integer groups separated by dots.
private static int compareDotNums(String str1, String str2) {
if (str1 != null && str2 != null) {
String[] split1 = str1.split("\\.");
String[] split2 = str2.split("\\.");
if (split1.length != split2.length)
throw new IllegalArgumentException("Input length mismatch.");
int result = 0;
for (int i = 0; i < split1.length; i++) {
try {
result = Integer.valueOf(split1[i]).
compareTo(Integer.valueOf(split2[i]));
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"Illegal input. Not a number.");
}
if (result != 0)
break;
}
return result;
} else
throw new IllegalArgumentException("Non-null input required.");
}
Sample Output:
System.out.println(compareDotNums("202.10.200", "202.201.30")); // -1
System.out.println(compareDotNums("202.210.200", "202.201.30")); // 0
System.out.println(compareDotNums("202.201.30", "202.201.30")); // 1
System.out.println(compareDotNums("202.201.30.110", "202.201.30.128")); // -1
System.out.println(compareDotNums("202.201.30.128", "202.201.30.128")); // 0
System.out.println(compareDotNums("202.201.30.210", "202.201.30.128")); // 1
I have two arrays:
arrayA = {"b","c","a"}
arrayB = {"99","11","22"}
How do I sort them together so that arrayA = {"a","b","c"} and arrayB = {"22","99","11"}?
I have made one alphanumeric sorting programm Check it out.
import java.util.Arrays;
import java.util.Comparator;
public class AlphanumericSorting implements Comparator {
public int compare(Object firstObjToCompare, Object secondObjToCompare) {
String firstString = firstObjToCompare.toString();
String secondString = secondObjToCompare.toString();
if (secondString == null || firstString == null) {
return 0;
}
int lengthFirstStr = firstString.length();
int lengthSecondStr = secondString.length();
int index1 = 0;
int index2 = 0;
while (index1 < lengthFirstStr && index2 < lengthSecondStr) {
char ch1 = firstString.charAt(index1);
char ch2 = secondString.charAt(index2);
char[] space1 = new char[lengthFirstStr];
char[] space2 = new char[lengthSecondStr];
int loc1 = 0;
int loc2 = 0;
do {
space1[loc1++] = ch1;
index1++;
if (index1 < lengthFirstStr) {
ch1 = firstString.charAt(index1);
} else {
break;
}
} while (Character.isDigit(ch1) == Character.isDigit(space1[0]));
do {
space2[loc2++] = ch2;
index2++;
if (index2 < lengthSecondStr) {
ch2 = secondString.charAt(index2);
} else {
break;
}
} while (Character.isDigit(ch2) == Character.isDigit(space2[0]));
String str1 = new String(space1);
String str2 = new String(space2);
int result;
if (Character.isDigit(space1[0]) && Character.isDigit(space2[0])) {
Integer firstNumberToCompare = new Integer(Integer
.parseInt(str1.trim()));
Integer secondNumberToCompare = new Integer(Integer
.parseInt(str2.trim()));
result = firstNumberToCompare.compareTo(secondNumberToCompare);
} else {
result = str1.compareTo(str2);
}
if (result != 0) {
return result;
}
}
return lengthFirstStr - lengthSecondStr;
}
public static void main(String[] args) {
String[] alphaNumericStringArray = new String[] { "NUM10071",
"NUM9999", "9997", "9998", "9996", "9996F" };
Arrays.sort(alphaNumericStringArray, new AlphanumericSorting());
for (int i = 0; i < alphaNumericStringArray.length; i++) {
System.out.println(alphaNumericStringArray[i]);
}
}
}
Here is the output:
9996
9996F
9997
9998
NUM9999
NUM10071
Use Arrays.sort(arrayB). You can even supply your custom Comparator to affect the sorting.
This link will help you Try array.sort(Arg);
http://www.leepoint.net/notes-java/data/arrays/70sorting.html
If you will be using the same letters and only 1 digit from 0 to 9, then, you can sort it in the same manner you have sorted the first array. If you intend to throw in more letters with more numbers, you will have to implement your own custom comparator (assuming the default behaviour does not suit you).
The answer to the question as written seems so obvious that I think we are not understanding what you are really asking.
I'm guessing that what you are really asking is how to sort one array, and reorder the second array based on how the sort reordered the first array. (Your example is poorly chosen to illustrate this ... but it does in fact doing this.)
Assuming that's what you mean, the simplest way to do this is to turn the two arrays into a single array of pairs, sort the pairs based on the first field, and then use the sorted pair list to repopulate the original arrays.
The (possible) snag is that the total ordering of the second array is indeterminate if the sort is not stable. (Or to put it another way, if there are duplicates in arrayA, then the relative order of the corresponding arrayB elements cannot be predicted.) There are ways to deal with this.
you can use
Arrays.sort(arrayB);
Output is
C1
C2
C3
arrayB = {"22","99","11"}
Arrays.sort(arrayB);
Output:
11
22
99