I was wondering if it is possible to do a select * where value is in Java String[] or do I need to build a string of values from the string array first?
I am trying to find the best way of doing this technically without singular selects or building a string of values from the array.
Thanks for your time.
String[] lookupValues = new String[]{"1", "2", "3", "4"};
Select * from database where value in (lookupvalues)
try Arrays.toString(lookupvalues) or write a utility function.
public String toString(String[] values, boolean addQuotes) {
StringBuilder buff = new StringBuilder();
for(String value : values) {
if(addQuotes) {
buff.append(String.format("\"%s\"", value)).append(",");
} else {
buff.append(value).append(",");
}
}
buff.deleteCharAt(buff.length()-1); // delete the last comma
return buff.toString();
}
Are you looking to search for a string in array? If yes, you might want to look at Collections.binarySearch() or Arrays.binarySearch() - but please not that the collections or arrays need to be sorted before doing binary search
I know that this is not a direct answer to your question considering only arrays. I suggest you to use Guava since it offers a implementation of filter on Java Collections. Using proven libraries will give you flexibility if you use different kind of filters.
You can easily convert your array into proper collection
String[] lookupValues = new String[]{"1", "2", "3", "4"};
List<String> list = new ArrayList<String>(Arrays.asList(lookupValues));
And filter it with Guava filters:
Collection<String> filtered = Collections2.filter(list,
Predicates.containsPattern("3"));
print(filtered);
will find
3
If you want filtered collection as a list, you can use this something like this from Guava:
List<String> filteredList = Lists.newArrayList(Collections2.filter(
list, Predicates.containsPattern("3")));
Related
I'm have defined a list like the below
List<String> list = List.of("val1", "val2", "val3");
Now I have the below String
String myStr = "rel1,wel12,val1";
Now I need to check if the String has anyone one of the elements of the list(in the above case its true as it has val1, next is get that value into a variable
I have tried the below and it works, but I'm sure there is a better way to do that using any of the Collections libraries
List<String> list = List.of("val1", "val2", "val3");
String myStr = "rel1,wel12,val1";
String matchedStr =StringUtils.EMPTY;
String[] vals = myStr.split(",");
for(String val:vals) {
if(list.contains(val){
matchedStr=val;
break;
}
}
You can use Java Streams to get the first String that match:
Optional<String> result = Stream.of(vals).filter(list::contains).findFirst();
Your way is alright if the lists aren't too big. I am considering the string as a list too because it can be made one from splitting it as you've done already. You can make a set from the bigger one, and iterate on the smaller one.
Another way to go would be to find the intersection of two lists.
List<String> list = Arrays.asList("red", "blue", "blue", "green", "red");
List<String> otherList = Arrays.asList("red", "green", "green", "yellow");
Now we can find the inttersection:
Set<String> result = list.stream()
.distinct()
.filter(otherList::contains)
.collect(Collectors.toSet());
The result should contain "red" and "green".
Some more info on collectors.
Depending on the possible values in the problem domain, there may be no need to split the input string. Just call String#contains.
If so, you can flip your logic. Rather than loop on the split parts, loop on the target list of strings. For each string in the list, ask if your unprocessed input string contains that element. If yes, bail out of the loop.
Tip: If this code is in a method returning a string, and returns null if no match was found, learn about returning an Optional.
I would favour Zobayer's answer, or using List#retainAll.
final List<String> first = List.of("one", "two", "three");
final List<String> out = new ArrayList<>(Arrays.asList("five,four,three".split(",")));
out.retainAll(first);
out contains the single entry, "three".
So I am trying to create an for loop to find unique elements in a ArrayList.
I already have a ArrayList stored with user input of 20 places (repeats are allowed) but I am stuck on how to count the number of different places inputted in the list excluding duplicates. (i would like to avoid using hash)
Input:
[park, park, sea, beach, town]
Output:
[Number of unique places = 4]
Heres a rough example of the code I'm trying to make:
public static void main(String[] args) {
ArrayList<City> place = new ArrayList();
Scanner sc = new Scanner(System.in);
for(...) { // this is just to receive 20 inputs from users using the scanner
...
}
# This is where i am lost on creating a for loop...
}
you can use a Set for that.
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Store the list data to the Set.Set will not have duplicates in it, so the size of set will be the elements without duplicates.
use this method to get the set size.
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#size()
Sample Code.
List<String> citiesWithDuplicates =
Arrays.asList(new String[] {"park", "park", "sea", "beach", "town"});
Set<String> cities = new HashSet<>(citiesWithDuplicates);
System.out.println("Number of unique places = " + cities.size());
If you are able to use Java 8, you can use the distinct method of Java streams:
int numOfUniquePlaces = list.stream().distinct().count();
Otherwise, using a set is the easiest solution. Since you don't want to use "hash", use a TreeSet (although HashSet is in most cases the better solution). If that is not an option either, you'll have to manually check for each element whether it's a duplicate or not.
One way that comes to mind (without using Set or hashvalues) is to make a second list.
ArrayList<City> places = new ArrayList<>();
//Fill array
ArrayList<String> uniquePlaces = new ArrayList<>();
for (City city : places){
if (!uniquePlaces.contains(city.getPlace())){
uniquePlaces.add(city.getPlace());
}
}
//number of unique places:
int uniqueCount = uniquePlaces.size();
Note that this is not super efficient =D
If you do not want to use implementations of Set or Map interfaces (that would solve you problem with one line of code) and you want to stuck with ArrayList, I suggest use something like Collections.sort() method. It will sort you elements. Then iterate through the sorted array and compare and count duplicates. This trick can make solving your iteration problem easier.
Anyway, I strongly recommend using one of the implementations of Set interface.
Use following answer. This will add last duplicate element in distinct list if there are multiple duplicate elements.
List<String> citiesWithDuplicates = Arrays.asList(new String[] {
"park", "park", "sea", "beach", "town", "park", "beach" });
List<String> distinctCities = new ArrayList<String>();
int currentIndex = 0;
for (String city : citiesWithDuplicates) {
int index = citiesWithDuplicates.lastIndexOf(city);
if (index == currentIndex) {
distinctCities.add(city);
}
currentIndex++;
}
System.out.println("[ Number of unique places = "
+ distinctCities.size() + "]");
Well if you do not want to use any HashSets or similar options, a quick and dirty nested for-loop like this for example does the trick (it is just slow as hell if you have a lot of items (20 would be just fine)):
int differentCount=0;
for(City city1 : place){
boolean same=false;
for(City city2 : place){
if(city1.equals(city2)){
same=true;
break;
}
}
if(!same)
differentCount++;
}
System.out.printf("Number of unique places = %d\n",differentCount);
So lets say I want to make an array of nine country names. I have the code to create the array:
String[] countryName = new String[9];
Lets say I wanted to add nine unique country names to this array. I could do something like this:
countryName[0] = "Mexico";
countryName[1] = "United States";
and so on. But is there a way I could add all of the names at once? Maybe something like an add() statement?
you can initialize the array with:
String[] countryName = new String[]{"Mexico", "Italy", "Spain"};
You can write simple utility method using varargs
static void addAll(String[] arr, String ... elements)
{
if (elements != null)
{
System.arraycopy(elements, 0, arr, 0, elements.length);
}
}
Usage
addAll(countryName, "Mexico", "US", "Ukraine");
Use an ArrayList this has the Add method.
ArrayList<String> countryName = new ArrayList<String>();
countryName.add("Mexico");
countryName.add("United States");
countryName.add("Dominican Republic");
countryName.add("...");
Enlist all contries in String and use split
String str="Country1,Country2,Country3";
String array[]=str.split(",");//You even don't need to initialize array
Use delimeter carefully to avoid extra spaces.
NOTE:
As this is one of the ways to add values to array but still I suggest you to go for Michel Foucault's answer as split will have more overhead than direct initialization.
I have a List<String> I need to find whether the particular string exists inside a List or not.
for Eg:
String str = "apple";
List<String> listObject = Lists.newArrayList("apple", "orange", "banana");
I need to find whether str exists in listObject or not using Google Guava.
So I need a true or false result.
How can I achieve this?
This is a standard part of the Java Collections API:
boolean exists = listObject.contains(str);
I'm agree that this can be done (and should, maybe) with the standard Collections API, but anyway, in Guava you can do it like this:
List<String> strList = Arrays.asList(new String[] {"one", "two", "3", "4"});
boolean exists = FluentIterable.from(strList).contains("two");
I read data from a text file, so there may be:
John
Mary
John
Leeds
I now need to get 3 unique elements in the ArrayList, because there are only 3 unique values in the file output (as above).
I can use a HashTable and add information to it, then simply copy its data into the List.
Are there other solutions?
Why do you need to store it in a List? Do you actually require the data to be ordered or support index-based look-ups?
I would suggest storing the data in a Set. If ordering is unimportant you should use HashSet. However, if you wish to preserve ordering you could use LinkedHashSet.
If you have a List containing duplicates, and you want a List without, you could do:
List<String> newList = new ArrayList<String>(new HashSet<String>(oldList));
That is, wrap the old list into a set to remove duplicates and wrap that set in a list again.
You can check list.contains() before adding.
if(!list.contains(value)) {
list.add(value);
}
I guessed it would be obvious! However, adding items to a HashSet and then creating a list from this set would be more efficient.
Use a set instead of a list. Take a look at here: Java Collections Tutorials and specifically about Sets here: Java Sets Tutorial
In a nutshell, sets contain one of something. Perfect :)
Here is how I solved it:
import groovy.io.*;
def arr = ["5", "5", "7", "6", "7", "8", "0"]
List<String> uniqueList = new ArrayList<String>(new HashSet<String>( arr.asList() ));
System.out.println( uniqueList )
Another approach would be to use Java 8 stream's distinct
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
// public static void main(String args[]) ...
// list of strings, including some nulls and blanks as well ;)
List<String> list = Arrays.asList("John", "Mary", "John", "Leeds",
null, "", "A", "B", "C", "D", "A", "A", "B", "C", "", null);
// collect distinct without duplicates
List<String> distinctElements = list.stream()
.distinct()
.collect(Collectors.toList());
// unique elements
System.out.println(distinctElements);
Output:
[John, Mary, Leeds, null, , A, B, C, D]
List<String> distinctElements = list.stream()
.distinct().filter(s -> s != null && s != "")
.collect(Collectors.toList());
This will collect the distinct items and also avoid null or empty String
class HashSetList<T extends Object>
extends ArrayList<T> {
private HashSet<Integer> _this = new HashSet<>();
#Override
public boolean add(T obj) {
if (_this.add(obj.hashCode())) {
super.add(obj);
return true;
}
return false;
}
}
I now use those kind of structure for little programs, I mean you have little overhead in order to have getters and setters but uniqueness. Moreover you can override hashCode to decide wether your item equals another one.