I have a method that takes vararg Array of strings
void count(long delta, String... tags);
I have a predefined array of tags for the most cases
String[] tags = { "foo_tag:Foo",
"bar_tag:Bar",
"baz_tag:Baz"
};
and only one tag to be added to predefined tags in each call "project_id:12345"
So the call of count should look like this:
count(delta, "foo_tag:Foo", "bar_tag:Bar", "baz_tag:Baz", "project_id:12345");
How can I simply create a new array containing my existing one plus additional element just in place of calling the method?
Something like this hypothetical Arrays.append method:
count(delta, Arrays.append(tags, "project_id:12345"));
This is storing statistics operation, not a business logic, so I want this operation to be as fast as possible.
Currently, I have helper method appendTag, but it doesn't look elegant as for me
private String[] appendTag(String[] tags, String s)
{
String[] result = new String[tags.length + 1];
System.arraycopy(tags, 0, result, 0, tags.length);
result[result.length-1] = s;
return result;
}
In java, arrays have a fixed size so it won't be possible to extend an array by appending new elements to it.
You will need to create a new array with a larger size and copy the first one elements into it, then add new elements to it, but it's not dynamic yet.
What I can suggest is to use a Collection maybe an ArrayList you will profit from its built-in methods like .add()
There is no easy way to expand an array by one element and add something new. But if you were working with a list instead, you could easily add a new element and then convert it to an array when calling the method:
String[] tags = { "foo_tag:Foo",
"bar_tag:Bar",
"baz_tag:Baz"
};
List<String> tagList = new ArrayList<String>(Arrays.asList(tags));
tagList.add("project_id:12345");
count(delta, tagList.toArray(new String[0]));
If you think you will have a long term need for this, then perhaps consider changing the implementation of count() to use a list instead of an array. You could also overload this method and expose a version which accepts list instead of array.
Related
I have an ArrayList (~900 entries) containing arrays of user information:
[swaschit, Sophia Waschitz, Dormant, Inactive, 1/1/2018]
[kolanday, Kyle Olanday, Dormant, Inactive, 1/1/2018]
[npowers, Neil Powers, Assigned, Active, 2/11/2018]
I want to generate an array from this list containing only the first elements of each object:
[swaschit, kolanday, npowers, ...]
What is the most efficient way of doing this?
One way is to use a Stream and map each of the inner arrays to its first element:
List<String> firstElements = yourList.stream()
.map(x -> x[0].toString()) // you might need toString() here if your array is an Object[]
.collect(Collectors.toList());
If you would like an array of strings instead:
String[] firstElements = yourList.stream()
.map(x -> x[0].toString()) // you might need toString() here if your array is an Object[]
.toArray(String[]::new);
I also suggest you to not use nested arrays like this. You should create a class with the properties you want to store and create a List of your class.
As I suppose the first entry is unique (as it seems to be a username), I would suggest using a Map. That way, you could simply list the keys.
HashMap<String,ArrayList<String>> hashmap=new HashMap<>();
Alternatively, you could simply create a class containing that information, to avoid needing the use of an ArrayList, but I don't know if this is an option.
As pointed out using an appropriately designed Object rather than an array of such heterogeneous data (guessing they are Strings in reality).
If you insist on keeping it the way you have though, you just need to allocate a new array with the size of the original ArrayList and iterate through, fetching the desired column. Assuming ArrayList<String[]> list
int size = list.size();
String[] firstColumn = new String[size];
for (int i = 0; i < list.size(); i++) {
firstColumn[i] = list.get(i)[0];
}
I suppose that you can do
list.stream().map(array -> array[0].toString()).toArray()
I have a Collection of elements and a single element. I want my getter function looks a little like this
public List<Element> getElements(boolean includeOtherElement){
if (includeOtherElement){
return elements + otherElement; //Obviously this doesn't work, but I'm looking for something that would work like this
}
return elements;
}
Is there a way I could acheive this behavior in a single line, such as with the Stream API or something similar?
EDIT:
I have since realized that I should not be modifying state in a getter method.
If you don't want to add otherElement to the elements list but still want to return a list, you will have to provide a new list.
Simple way:
public List<Element> getElements(boolean includeOtherElement){
if (includeOtherElement){
List<Element> extendedList = new ArrayList<>(elements);
extendedList.add(otherElement);
return extendedList;
}
return elements;
}
This would create a shallow copy of your list.
If you really want to, you could provide your own list implementation, which delegates the first indices to the elements list and the last index to the otherElement;
Usually you do not want your getter function to be changing variables. I would recommend doing something like temp = elements to return a temp variable, with the extra element added via temp.add(otherElement). This way you will not change your current variable while still eliciting the same behavior.
I'm not sure if this answer will work exactly for you but I think it is a good example of something that is possible with the API. The reason that it may or may not be usable in a particular case is that it depends on the location of the extra element(s) being constant in the list.
Suppose it was the case that you didn't want to create a copy of the list, because you actually wanted whoever calls the getter to be able to modify the list. Or, suppose that you just didn't want to make a defensive copy of the list, perhaps because the list is very, very large. In these cases you don't want to add or remove the extra element from the list, you want to return a view of the list which either includes or excludes the extra element.
This is actually possible with existing API, using the List.subList(int, int) method. subList doesn't create a copy, like e.g. String.substring(...) does. Rather, the returned sublist is mutable (if the original list was), and changes to the sublist show through to the original list.
(Though I should note that the semantics of the sublist become undefined if the backing list is structurally modified, i.e. you shouldn't add/remove to and from the original list while keeping a reference to the sublist. If you change the original list through a reference other than the sublist, you have to create a new sublist.)
So what you could do is keep a complete list with all of the elements, then return a sublist of the range which excludes the element(s) you don't want to return.
This could also be used in conjunction with Collections.unmodifiableList(List) if the code which calls the getter is not supposed to be able to mutate the list.
Here's an example which shows this in action:
import java.util.*;
class Example {
public static void main (String[] args) {
Example e = new Example();
List<Object> sub = e.getList(false);
// sublist is [1, 2, 3]
System.out.printf("sublist is %s%n", sub);
sub.add(0, -1);
sub.add(1, 0);
sub.add(5);
// sublist is [-1, 0, 1, 2, 3, 5]
System.out.printf("sublist is %s%n", sub);
List<Object> all = e.getList(true);
// full list is [element0, -1, 0, 1, 2, 3, 5]
System.out.printf("full list is %s%n", all);
// As a side-note, this sequence of calls is
// e.g. what you aren't supposed to do:
// all.add(something); // <- structural modification
// sub.add(another); // <- this is undefined
// You have to make a new sublist first:
// sub = e.getList(false);
// sub.add(another); // <- this is fine now
}
List<Object> objects = new ArrayList<Object>();
Example() {
objects.add("element0");
objects.add(1);
objects.add(2);
objects.add(3);
}
List<Object> getList(boolean includeElement0) {
if (includeElement0) {
return objects;
} else {
return objects.subList(1, objects.size());
}
}
}
Here is the example on Ideone: http://ideone.com/PloZCh.
Also, while not returning a List, this can be done by returning a Stream:
Stream<E> stream = list.stream();
if (includeOtherElement) {
return Stream.concat(stream, Stream.of(otherElement));
} else {
return stream;
}
I suppose this may be the canonical way to do such a thing in Java 8.
If I have an observableList data1 = FXCollections.observableArrayList();
I want to stick it in an array because I have a bunch of them.
Can I do that ?
If yes, whats the syntax ?
List interface provides a method called toArray() to convert a list to array. This should do:
data1.toArray();
EDIT
As per the questioner input, you may need this:
observableList[] observableListArray = new observableList[SIZE_YOU_NEED];
observableListArray[index] = data1;
I was wondering if it is possible to convert an Object into something else.
I have a Object which contains a series of numbers in a random order such as: 3, 4, 2, 5, 1 and wondering if I am able to turn it into an int[] or select certain elements from it, as in a number from the sequence?
EDIT:
so some of the code i have is:
//This contains all the different combinations of the numbers
ArrayList routePop4 = new ArrayList();
//This picks out the first one, just as a test
Object test = routePop4.get(0);
But the idea is that I want to loop through each element of test.
An Object cannot "contain a series of numbers". However many subclasses of Object, such as all of the Collections can "contain a series of numbers", and they come with a toArray() method to turn the contents of the collection into an array.
If you have a collection, but only have access to it as an Object, you need to cast it before you can work with it properly:
ArrayList<Integer> list = (ArrayList<Integer>)test;
Integer[] arr = list.toArray(new Integer[]{});
It's fairly rare in day-to-day Java to actually be working with variables cast as Object, if you are, it should be a red flag that you may be doing something wrong. You can use generics to allow objects that contain other objects to do so generically, like so:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); // Can only add integers, list.add("a string") would fail at compile time
int n = list.get(0); // no need to cast, we know list only contains Integers
If you aren't using a Collection, you'll presumably need to roll your own, as Luke Taylor's answer suggests. That said, you'll get better answers if you can provide more information, the current text of your question doesn't make sense in a Java context.
After seeing your edit, I recommend taking advantage of generics.
When you declare an ArrayList you can indicate what kind of objects it's going to contain.
For example, if you know your ArrayList will contain Strings, you would do this:
List<String> myList = new ArrayList<String>();
If each element of your list is an array of Integers, you would do this:
List<Integer[]> listOfIntegerArrays = new ArrayList<Integer[]>();
Then you could get any element from your list and assign it to an Integer array like this:
Integer[] integerArray = listOfIntegerArrays.get(0);
Then you could iterate over every Integer in the list like this:
for (Integer loopInteger : integerArray) {
System.out.println("The value: " + loopInteger);
}
Some more reading on generics:
http://thegreyblog.blogspot.com/2011/03/java-generics-tutorial-part-i-basics.html
http://docs.oracle.com/javase/tutorial/java/generics/
You could do something like this:
int[] numbersFromObject = new int[yourObject.getAmountOfNumbers()];
// Initialize array with numbers from array
for(int i = 0; i < yourObject.getAmountOfNumbers(); i++) {
numbersFromObject[i] = yourObject.getNumber(i);
}
I'm not sure what methods your object contains, yet I'm sure you'll be able to adjust to the following mentioned above.
I hope this helps.
I am using Java to split a search query on it's spaces
example:
String[] queryParams = queryString.split(" ");
so search for "New York Yankees" will get put into an array of three elements.
Now, I want to iterate over each of those elements (regardless of the length of the query) and store them in their respective variables so I can dynamically populate another part of my program.
Thanks
A simple for loop can iterate over your array.
for(String elem : queryParams) {
//do whatever with elem
}
Then if you want to use those values in another method of your program I'd suggest you pass your array to your method or just pass a single value (if you don't need every values) by calling your method like that : aMethod(queryParams[*anIndex*]); (in which case you wouldn't need to iterate on your array and assign to variable.
If you really want to assign your values to ids, maybe you could put them in a map in your for loop.
Why can't you use a simple for loop ?
for(int i = 0; i<queryParams.length; i++) {
// do something with queryParams[i]
}