Reputation: 4760
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?
Upvotes: 0
Views: 77
Reputation: 942
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
Upvotes: 1
Reputation: 176
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);
}
Upvotes: 0
Reputation: 48434
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
...
Upvotes: 3