I have an ArrayList containing strings retrieved from a database. The strings are tags for individual posts of a blog, for example:
video, java, php, xml,
css, java, foo, bar,
xml, php, foo, bar, dog
I am attempting to loop through the list. Split each string by their commas into an array and check if my uniqueTag array doesn't contain an element from the split array. If it doesn't, add it to the uniqueTag array.
This is how far I've got:
List<String> tagList = conn.getAllTags();
String[] uniqueTags;
for(String item: tagList){
// split the row into array of comman seperated elements
String[] splitItem = item.split(",");
for(int i=-1; i<=splitItem.length; i++){
// compare this element with elements in uniqueTags
// and if it doesn't exit in uniqueTags
// add it.
}
}
How do I compare and dynamically build the uniqueTags array?
I would use a Set<String> to prevent duplicate values.
Something along the lines of:
Set<String> uniques = new HashSet<String>();
for(String item: tagList){
// split the row into array of comman seperated elements
String[] splitItem = item.split(",");
for (String item: splitItem) {
uniques.add(item.trim()); // trimming whitespace and adding to set
...
Why do not you try something like this.
Create a List<String> splitIteams of split items and do
List<String> distinct = splitItems.stream().distinct().collect(Collectors.toList());
System.out.printf("Split Items : %s, Distinct list : %s ", splitItems, distinct);
Edit - deleted one extra %s
public static void compareArrays(int[] array1, int[] array2) {
boolean b = true;
if (array1 != null && array2 != null){
if (array1.length != array2.length)
b = false;
else
for (int i = 0; i < array2.length; i++) {
if (array2[i] != array1[i]) {
b = false;
}
}
}else{
b = false;
}
System.out.println(b);
}
Related
I have a sorted array list with 6 elements.The first 5 elements have some value, and the 6th one is empty.
I want to loop through this ArrayList, and compare the first 5 elements of first record, with the same elements in next record. If any one of the element is different, then populate 6th element.
Anyone know an easier and faster approach to do that?
Thanks
Angad
First split the all records into many String[], then parse all values in each. After that you can compare the current record with the first one. Here is an example:
public class StringComparison {
ArrayList<String[]> list = new ArrayList<String[]>();
public void comapreStrings() {
// The list you are comparing everything to
String[] firstRecord = list.get(0);
for(int n = 1; n < list.size(); n++) {
String[] currentRecord = list.get(n);
for (int i = 0; i < currentRecord.length; i++) {
String val1 = firstRecord[i];
String val2 = currentRecord[i];
if (val1.equals(val2)) {
// The two strings are the same
} else {
// Replace "a value" with whatever you want to fill the 6th element with
currentRecord[5] = "a value";
}
}
}
}
Maybe this could be an alternative to think about:
public String[] generateFirstRow(int startingRow) {
final String[] row1 = rowList.get(startingRow);
final String[] row2 = rowList.get(startingRow + 1);
final List<String> list1 = Arrays.stream(row1).collect(toList());
final List<String> toAdd = Arrays.stream(row2).parallel().sorted().filter(s -> !list1.contains(s)).collect(Collectors.toList());
if (list1.get(list1.size() - 1) == "") {
list1.set(list1.size() - 1, toAdd.get(0));
return list1.toArray(new String[0]);
}
return new String[0];
}
Now you can call this per row you have untill the pre-last one.
I want to display the contents of an array of linked lists. Each linked list contains a String array. The content of the array of linked lists is displaying as [[[Ljava.lang.String;#15db9742], [[Ljava.lang.String;#6d06d69c], [[Ljava.lang.String;#7852e922]]. How do I solve this?
public class LinkedListOfStringArrays {
public static void main(String[] args) {
LinkedList<String[]> Values[] = new LinkedList[3];
for (int i = 0; i < 3; i++){
Values[i] = new LinkedList<String[]>();
}
String[] first = {"first element", "ABC"};
String[] second = {"second element", "DEF"};
String[] third = {"third element", "GHI"};
Values[0].add(first);
Values[1].add(second);
Values[2].add(third);
System.out.println(Arrays.toString(Values));
}
}
You will have to loop through the lists and output it manually:
// Loop through the Array of LinkedLists
for(LinkedList<String[]> list : Values) {
// Next loop through each of the lists
for(String[] keyValuePair : list) {
// Then output the values as you see fit
System.out.println(keyValuePair[0] + " - " + keyValuePair[1]);
}
}
This will give you the following output:
first element - ABC
second element - DEF
third element - GHI
In Java 8 you can try as
Stream.of(Values).
flatMap(list -> list.stream()).
forEach(values -> System.out.println(String.join("-",values)));
I have 2 string arrays.
string [] first = {"ajunkbc","ajunkHello","adedbc","abcjunk","add","ad","a","","junk","ajunk","aajunkbb"};
String [] second = {"abc","aHello","adedbc","abcjunk","add","ad","a","","junk","a","aajunkbb"};
I'd like the result of my merge() method to concatenate each element from the first array with the respective element of the second array separated by a comma.
Below is my code
private static String[] merge(String [] tests, String [] expectations){
List<String> testList = Arrays.asList(tests);
List<String> expectationsList = Arrays.asList(expectations);
List<String> retList = new ArrayList<String>();
for(String test : testList){
for(String val : expectationsList){
retList.add(test+","+val);
break;
}
}
This does not work. What's wrong with my code?
What's wrong is that you are looping over expectationsList and breaking out of the loop after the first iteration:
for(String val : expectationsList){
retList.add(test+","+val);
break; //<--- breaking out of loop after first iteration each time
}
So the result is that you are always retrieving the first element of expectationsList.
Since what you want is to loop over two arrays, you should use an index:
for (int i = 0; i < testList.size(); i++) {
retList.add(testList.get(i)+","+expectationsList.get(i));
}
Also, note that this implies that the size of testList is the same as the size of expectationsList. Your method should probably throw an exception if this is not the case.
Note that you do not need to convert the input arrays into lists. You can use them as-is.
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
String[] result = new String[tests.length];
for (int i = 0; i < tests.length; i++) {
result[i] = tests[i] + "," + expectations[i]);
}
return result;
}
Java 8 solution:
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
return IntStream.range(0, tests.length).mapToObj(i -> tests[i] + "," + expectations[i]).toArray(String[]::new);
}
You're iterating through each member of testList and then for each one, iterating through each member of expectationsList. You want to iterate through each of both of them together.
What you want to do is something like this:
private static String[] merge(String[] tests, String[] expectations) {
String[] result = new String[tests.length];
for(int i = 0; i < tests.length; i++) {
result[i] = tests[i] + "," + expectations[i];
}
return result;
}
This code makes the assumption that tests and expectations have the same length. You might want to do a check for that at the beginning:
if (tests.length != expectations.length) {
throw new IllegalArgumentException("tests and expectations are of different lengths")
}
Notice how now you're getting the element at the same index from both arrays.
Sidenote: You can iterate over arrays with the for each format. This works just fine:
String[] myStringArray = getStringArray();
for (String myString : myStringArray) {
// Do something
}
You don't need to convert to a List in order to iterate :)
I have function returning an ArrayList<String[]>.
How can I get values from this returning ArrayList<String[]>?
Here is an example of using a "for-each loop" to iterate through String elements in an ArrayList.
ArrayList<String> list = new ArrayList<String>();
...
// For every item in the list
for(String value: list) {
// print the value
System.out.println(value);
}
What is a "for-each" loop?
http://download.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
Also remember you can randomly access values in the ArrayList using the index.
ArrayList<String> list = new ArrayList<String>();
list.add("0");
list.add("1");
int index = 1;
list.get(index); // You get the value 1
foreach(object o in arrayList)
{
// cast to appropriate type
// eg string s = o as string;
// ...
}
ArrayList<String[]> list = new ArrayList<String[]>();
for(int i=0; i<list.size(); i++){
String[] stringArray = list.get(i);
for(String s : stringArray) {
System.out.println(s);
}
or
for(int j=0; j<stringArray.length; j++) {
System.out.println(stringArray[j]);
}
}
//If just print out
ArrayList<String[]> list = new ArrayList<String[]>();
...
for(String[] item : list) {
//Use Arrays.toString
System.out.println(Arrays.toString(item));
}
Each list entry is either an array of Strings or null.
If you're interested in the String[] objects, then I suggest using the enhanced for loop:
ArrayList<String[]> result = myMethodProvidingTheList();
for(String[] strings : result) {
if (strings != null {
doSomethingWith(strings);
}
}
If you need the values from the arrays now, use the same enhanced for loop for the array:
private void doSomethingWith(String[] strings) {
for (String string : strings) {
if (string != null) {
doSomethingWith(string);
}
}
}
How to remove null value from String array in java?
String[] firstArray = {"test1","","test2","test4",""};
I need the "firstArray" without null ( empty) values like this
String[] firstArray = {"test1","test2","test4"};
If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:
import java.util.ArrayList;
import java.util.List;
public class RemoveNullValue {
public static void main( String args[] ) {
String[] firstArray = {"test1", "", "test2", "test4", "", null};
List<String> list = new ArrayList<String>();
for(String s : firstArray) {
if(s != null && s.length() > 0) {
list.add(s);
}
}
firstArray = list.toArray(new String[list.size()]);
}
}
Added null to show the difference between an empty String instance ("") and null.
Since this answer is around 4.5 years old, I'm adding a Java 8 example:
import java.util.Arrays;
import java.util.stream.Collectors;
public class RemoveNullValue {
public static void main( String args[] ) {
String[] firstArray = {"test1", "", "test2", "test4", "", null};
firstArray = Arrays.stream(firstArray)
.filter(s -> (s != null && s.length() > 0))
.toArray(String[]::new);
}
}
It seems no one has mentioned about using nonNull method which also can be used with streams in Java 8 to remove null (but not empty) as:
String[] origArray = {"Apple", "", "Cat", "Dog", "", null};
String[] cleanedArray = Arrays.stream(firstArray).filter(Objects::nonNull).toArray(String[]::new);
System.out.println(Arrays.toString(origArray));
System.out.println(Arrays.toString(cleanedArray));
And the output is:
[Apple, , Cat, Dog, , null]
[Apple, , Cat, Dog, ]
If we want to incorporate empty also then we can define a utility method (in class Utils(say)):
public static boolean isEmpty(String string) {
return (string != null && string.isEmpty());
}
And then use it to filter the items as:
Arrays.stream(firstArray).filter(Utils::isEmpty).toArray(String[]::new);
I believe Apache common also provides a utility method StringUtils.isNotEmpty which can also be used.
If you actually want to add/remove items from an array, may I suggest a List instead?
String[] firstArray = {"test1","","test2","test4",""};
ArrayList<String> list = new ArrayList<String>();
for (String s : firstArray)
if (!s.equals(""))
list.add(s);
Then, if you really need to put that back into an array:
firstArray = list.toArray(new String[list.size()]);
Using Google's guava library
String[] firstArray = {"test1","","test2","test4","",null};
Iterable<String> st=Iterables.filter(Arrays.asList(firstArray),new Predicate<String>() {
#Override
public boolean apply(String arg0) {
if(arg0==null) //avoid null strings
return false;
if(arg0.length()==0) //avoid empty strings
return false;
return true; // else true
}
});
This is the code that I use to remove null values from an array which does not use array lists.
String[] array = {"abc", "def", null, "g", null}; // Your array
String[] refinedArray = new String[array.length]; // A temporary placeholder array
int count = -1;
for(String s : array) {
if(s != null) { // Skips over null values. Add "|| "".equals(s)" if you want to exclude empty strings
refinedArray[++count] = s; // Increments count and sets a value in the refined array
}
}
// Returns an array with the same data but refits it to a new length
array = Arrays.copyOf(refinedArray, count + 1);
Quite similar approve as already posted above. However it's easier to read.
/**
* Remove all empty spaces from array a string array
* #param arr array
* #return array without ""
*/
public static String[] removeAllEmpty(String[] arr) {
if (arr == null)
return arr;
String[] result = new String[arr.length];
int amountOfValidStrings = 0;
for (int i = 0; i < arr.length; i++) {
if (!arr[i].equals(""))
result[amountOfValidStrings++] = arr[i];
}
result = Arrays.copyOf(result, amountOfValidStrings);
return result;
}
A gc-friendly piece of code:
public static<X> X[] arrayOfNotNull(X[] array) {
for (int p=0, N=array.length; p<N; ++p) {
if (array[p] == null) {
int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
X[] res = Arrays.copyOf(array, m);
for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
return res;
}
}
return array;
}
It returns the original array if it contains no nulls. It does not modify the original array.
Those are zero-length strings, not null. But if you want to remove them:
firstArray[0] refers to the first element
firstArray[1] refers to the second element
You can move the second into the first thusly:
firstArray[0] = firstArray[1]
If you were to do this for elements [1,2], then [2,3], etc. you would eventually shift the entire contents of the array to the left, eliminating element 0. Can you see how that would apply?