Pass Collection of string to (String... values) - java

I have a very simple question.
This below method-
newColumnsPredicate
takes input as String... colNames
Below is the method signature as well-
public static SlicePredicate newColumnsPredicate(String... colNames) {
//Some code
}
And I have below collection of strings that I wanted to use in the above method-
final Collection<String> attributeNames
So I decide to use it something like this-
newColumnsPredicate(attributeNames.toString());
This is the right way to do this? As after I run my program, I don't get any data back so I am suspecting it might be possible the way I have added is wrong.
Can anyone help me with this?

String... is a vararg parameter. It is used to indicate that the parameter should either be an array of Strings, or as many String arguments as you like.
Calling toString() on the collection will merely return one string that combines all of the Strings it contains.
You should instead write something that converts your collection to an array, and then pass that in, like:
attributeNames.toArray(new String[attributeNames.size ()])

No, When you do a attributeNames.toString(), you are passing a single String to the method, with a square bracket around them, like "[a, b, c]", Where as your program expects something like "a", "b", "c".

Wouldn't the toArray()function be useful here?
public void test() {
Collection<String> collection = new HashSet<>();
newColumnsPredicate(collection.toArray(new String[collection.size()]));
}
public static SlicePredicate newColumnsPredicate(String... colNames) {
//stuff
}
EDIT:
Whoops, didn't see the other guy answered in the same way.

Related

How to call array out from Java method

I created an array Pages in method List.
Could you please advise how to call out one element Pages[1] when accessing method List() from other classes?
public List() {
String[] Pages = {
"www.cnn.com",
"www.bbc.com",
"www.yahoo.com",
};
Many thanks!
You can't call a localvariable from a method directly. You must return it somehow.
Btw, it looks like you don't understand really well how methods work in Java. You should check it.
Here's an example of what do you want to do:
public String[] listPages(){
String [] pages = {"www.cnn.com", "www.bbc.com", "www.yahoo.com"};
return pages;
}
Later if you want to use one of the elements of the array, you should do something like this:
public static void main(String[] args){
String[] res = listPages();
//now we want to print the element one: www.cnn.com
System.out.println(res[0]);
}
You need to create a class named List and a constructor for that class.
Also there are redundant ;, between the elements of the array.

Better way to convert an List<MyDataType> to List<String>

I am wondering if there isn't a better way to convert whole Lists or Collections as the way I show in the following code example:
public static List<String> getAllNames(List<Account> allAccounts) {
List<String> names = new ArrayList<String>(allAccounts.size());
for (Account account : allAccounts) {
names.add(account.getName());
}
return names;
}
Every time I produce a method like this, I start thinking, isn't there a better way? My first thought would be to create maybe a solution with some generics and reflections, but this seems maybe a bit over sized and maybe a bit to slow when it comes to performance?
Take a look at Google's Guava library
Something like this should do it
final List<String> names = Lists.transform(myObjs, new Function<MyObject, String>() {
public String apply(final MyObject input) {
return input.getName();
}
});
With Guava, there is a more functional approach:
return FluentIterable.from(allAccounts).transform(new Function<Account,String>(){
public String apply(Account account){return account.getName();}
}).toImmutableList()
But that essentially does the same thing, of course.
BTW: the difference between this answer and RNJ's is that in my case the list will be created once, while in the other answer it's a live view. Both versions are valid, but for different scenarios.
I actually have exactly this kind of method in my personal library.
public static <TSource,TTarget> List<TTarget> castList(List<TSource> sourceList)
{
List<TTarget> targetList = new ArrayList<TTarget>(sourceList.size());
for (TSource t : sourceList) {
//This will throw a ClassCastException if the types are not compatible
//Be carefull
targetList.add((TTarget)t);
}
return targetList;
}
Usage is very simple because the compiler infers the type for TTarget.
List<Object> objects = new ArrayList<Object>();
objects.add("One");
objects.add("Two");
List<String> strings = castList(objects);
Regarding the performance:
I think using generics is no problem here. But the need to copy the whole array is another story.
There is no better way. Casting is a difficult and dangerous thing. In your example, your are not able to cast a String to a MyDataType or vice versa, aren't you?
You might create an own List-Implementation with some kind of toStringList()-Method if you need these more often.
There's a simple way but it is not type safe
List<A> a = new ArrayList<A>();
List<B> b = (List)a;
but then you have to override the implementation of toString() method of your class to return the getName() value.
But there's no type checking,
And as mentioned you can of course do instead a loop and call getName on every object
You could try using the Iterables and Function classes from the Guava libraries. You can create a new type of an Iterable using,
Iterable<String> newTypeIterable = Iterables.transform(oldTypeIterable, new Function<MyDataType, String> () {
#Override
public String apply(MyDataType from)
{
return from.getName();
}
});
Turns out you can do this with the Lists class too!

String[] or ArrayList in Constructor?

I have to make a constructor for an ArrayList. So basically what I want is that this constructor makes an ArrayList.
public Recipe(String[] modifications){
The problem is, it should give something like(example):
String[] modifications = [heatup, cooldown, mix, heatup]
Will the constructor work like this:
Recipe(heatup, cooldown, mix, heatup)
or do I need to change it to somethign like:
Recipe(modifications){
this.myArrayList[1] = modifications[1]
.
.
.
}
thank you and sorry if there are some big mistakes in my code, still learning my Java code.
You can define it this way:
public Recipe(String... modifications)
This will give you a variable argument list, so your constructor will work like this: Recipe(heatup, cooldown, mix).
Inside of the constructor, you can use it just like an array.
change the constructor to varargs:
public Recipe(String ... modifications){
and you can access modifications as String[] however, that's an array, not an ArrayList. If you want an ArrayList, do something like this:
private final List<String> list;
public Recipe(String ... modifications){
this.list = new ArrayList<String>(Arrays.asList(modifications));
}
You could make a constructor with varargs parameters:
public Recipe(String... modifications){...}
then you can call it like this:
Recipe(heatup, cooldown, mix, heatup);
Note though that you should be careful with varargs parameters if you (plan to) have other constructor(s) with potentially conflicting parameter list. However, if this is your only constructor, varargs should be fine.
You could this in your constructor
ArrayList<String> list=new ArrayList<String>();
public Recipe(String[] modifications){
// String a[]={"asas"};
list.addAll(Arrays.asList(modifications));
The second one... of course you can use a for if you just want to copy the elements.
Also you can just copy the array passed by parameter into your class attribute / method variable, unless there is another motive not to do so.
Finally, remember that it would be something like Recipy(String[] modifications) {. You must define the type of the arguments.
And now really finally, myArrayList is a somewhat unfortunate name for an array (there is a class in the API called ArrayList).
What you want is to be able to pass an undetermined number of arguments:
public Recipe(String ... modifications) {
Inside the constructor, modifications is an array.
This will work with this:
new Recipe("heatup", "cooldown", "mix", "heatup");
and with this:
new Recipe();
and with this:
new Recipe("heatup", "mix");
You can use varargs:
public Recipe(String ... modifications) {
// now you can use modifications as an array
for (int f = 0; f < modifications.length; f++) {
System.out.println("#" + f + ": " + modifications[f]);
}
}
.
To use your class you just have to write:
Recipe myRecipe = new Recipe("heatup", "mix");
.

Java - ArrayList<Integer> as Parameter...?

I would like to know how to create a method which takes an ArrayList of Integers (ArrayList) as a parameter and then display the contents of the ArrayList?
I have some code which generates some random numbers and populates the ArrayList with the results, however I keep having errors flag up in eclipse when attempting to create this particular method.
Here is what I have so far:
public void showArray(ArrayList<Integer> array){
return;
}
I know that it is very basic, but I am unsure exactly how to approach it - could it be something like the following?
public void showArray(ArrayList<Integer> array){
Arrays.toString(array);
}
Any assistance would be greatly appreciated.
Thank you.
I'm assuming this is a learning exercise. I'll give you a few hints:
Your method is named showArray, but an ArrayList<T> is of type List<T>, and is not an array. More specifically it is a list that is implemented by internally using an array. Either change the parameter to be an array or else fix the name of the method.
Use an interface if possible instead of passing a concrete class to make your method more reusable.
Minor point: It may be better to have your method return a String, and display the result outside the method.
Try something like this:
public void printList(List<Integer> array) {
String toPrint = ...;
System.out.println(toPrint);
}
You can use a loop and a StringBuilder to construct the toPrint string.
Is there any reason why System.out.println( array ); wouldn't work for you?
Output will be like:
[1, 2, 3]
If you are looking to print the array items, try
public void showArray(ArrayList<Integer> array){
for(int arrayItem : array)
{
System.out.println(arrayItem);
}
}
This sounds like someone wants us to do their homework. You don't have to return anything if you are just displaying it, and if the method has a void return type. I don't know exactly what you want but is it something along the lines of System.out.println(array.elementAt(index))? then you would need a loop.

Java: Using one function to return a few different types of value

I have a readData() function that reads files a returns a few different objects of parsed data. Right now, the return type of readData() is Object[]:
Object[] data = readData();
MyGenome genome = data[0];
Species[] breeds = data[1];
//etc
This feels awkward. Is there a better way to return this data? I don't want to have separate functions like readGenome() and readSpecies() because that would require iterating over the files twice. Also, I'd rather wrap up all the gathering of data in one function.
A similar issue: a function that returns a match of at least four characters between two strings:
public int[][] findMatch(String g0, String g1) { /* cool stuff */ }
//...
int[][] bounds = findMatch("ACOIICOCOCICOICA", "AOCCCCCCICCIIIIIOIAOCICOICOICA");
where bounds[0][0] is the left bound on the g0, bounds[0][1] is the right bound on g0, bounds[1][0] is the left bound on g1, etc. This also feels sort of awkward. It is difficult to code with the result without continuously looking up the keys.
Create a new Class:
class MyAnalysedGenome {
MyGenome genome;
Species[] species
...
}
and return that. You'll probably find you have other functionality that should go in there too. Perhaps the code that surrounds your getData() call.
How about using a strongly typed class to represent the complex return type of readData()?
public class Taxonomy
{
public MyGenome genome;
public Species[] breeds;
//etc
{
Taxonomy data = readData();
You can do the same thing for your search bounds problem
public class SearchBoundary
{
public int left;
public int right;
}
SearchBoundary resultBounds = findMatch(searchBounds);
For the first issue,couldn't you simply use an intermediate data representation ? I mean you could read your file once, which would give you the file content (that you could format the way you want), and then create two methods readGenome() and readSpecies() that would take this file content as a parameter.
You can create a class that have genome and species as fields.
...
class DataToBeRead {
MyGenome genome;
Species[] breeds;
}
...
DataToBeRead data = readData();
MyGenome genome = data.genome;
Species[] breeds = data.breeds;
You can make the class private if you do not think anybody else will used it or make it public if someone else will use it.
You can also make it static if you do not want to create a separate file for it.
Hope this helps.

Categories