Is there a simple way in Java (that doesn't involve writing a for-loop) to create an array of objects from a property of another array of different objects?
For example, if I have an array of objects of type A, defined as:
public class A {
private String p;
public getP() {
return p;
}
}
I want to create an array of Strings that contains the value of A[i].p for each i.
Essentially, I'm I want to do this: Creating an array from properties of objects in another array, but in Java.
I attempted to use Arrays.copyOf(U[] original, int newLength, Class<? extends T[]> newType) along with a lambda expression, but that didn't seem to work. What I tried:
Arrays.copyOf(arrayA, arrayA.length, (A a) -> a.getP());
With Java 8, you can use the Stream API and particularly the map function:
A[] as = { new A("foo"), new A("bar"), new A("blub") };
String[] ps = Stream.of(as).map(A::getP).toArray(String[]::new);
Here, A::getP and String[]::new are method/constructor references. If you do not have a suitable method for the property you want to have, you could also use a lambda function:
String[] ps = Stream.of(as).map(a -> a.getP()).toArray(String[]::new);
This is where a powerful concept in functional programming called map is useful. Here's how map is defined:
map :: (a -> b) -> [a] -> [b]
Thus, map is a function that takes a function (that takes a and returns b) and a list and returns a list. It applies the given function to each element of the given list. Thus map is a higher order function.
In Java 8, you can use this idiom if you can convert the array into a stream. This can be done simply:
Arrays.stream(array).map(mappingFunction);
where the mappingFunction takes an element from stream (say of type A) and converts it to another (say of type B). What you now have is a stream of B's, which you can easily collect in a collector (e.g. in a list, or an array) for further processing.
Related
There are two existing methods named getDetails(...). One expects a minimum of one mandatory parameter and the other expects a collection (doesn't validate the content/size of the collection).
The problem is that the collection is sometimes passed as empty and according to my business case, I always expect a minimum of one value, to be passed. So, I need to make that method private, which accepts Collections.
// There are two params, to make sure that at-least one is passed by the caller
public static CustomerContext getDetails(int id, int... ids) {
Collection<Integer> idCollection = Instream.of(ids).boxed().collect(Collectors.toSet());
if(!idCollection.contains(id)){
idCollection.add(id);
}
return getDetails(idCollection);
}
I'm planning to make the below method scope to private so that the callers would not call this method with Zero attributes.
public static CustomerContext getDetails(Collection<Integer> idCollection) {
return getDetails(idCollection,false);
}
One of the caller methods is passing Collection object to getDetails like below,
CustomerContext.getDetails(id.getDetails().values());
The id.getDetails() is as below,
public Map<Id,Integer> getDetails(){
return Collections.unmodifiableMap(details);
}
I'm looking for a way to convert the collection id.getDetails().values() into int[] for passing to getDetails(int id,int... ids) instead of calling getDetails(Collection<Integer> idCollection).
I could cast the collection to Integer[] as below,
(Integer[])id.getDetails().values().toArray()
I did not find a way to cast Collection to int[].
Any suggestions would be of great help.
I already referred to some of the existing questions but did not succeed to solve my issue:
Conversion of collection to int array
Convert java.util.Collections to Integer array
Collection to Integer[]
When you need to get a result of type Integer[], you have to provide a function as an argument while calling toArray(), there's no need to apply casting (if you're not passing a parameter toArray() returns an array Object[]).
Integer[] arr = id.getDetails().values().toArray(Integer[]::new);
Collection to int[]
There's no way convert a Collection of Integer type or an array Integer[] into an array int[] directly. It's not possible to obtain one from another simply by doing casting, these types are not compatible.
You have to iterate over the source and populate the newly created int[] array. It can be done either "manually" using a loop, or in a more convenient way with streams, the overall approach doesn't change.
That's how it can be done using Stream API:
int[] arr = id.getDetails().values().stream() // Stream<Integer> - stream of objects
.mapToInt(Integer::intValue) // IntStream - stream of primitives
.toArray();
You can't cast Collection<Integer> to int[], but you can create the array:
int[] values = id.getDetails().values().stream()
.mapToInt(n -> n)
.toArray();
An aside... this code:
if (!idCollection.contains(id)) {
idCollection.add(id);
}
May be changed to just:
idCollection.add(id);
because idCollection is a Set and that's how sets work. It matters not that it's declared as a Collection; it is a Set.
Maybe this is very simple but I'm actually a noob on Java 8 features and don't know how to accomplish this. I have this simple line that contains the following text:
"Key, Name"
and I want to convert that line into a String array, separating each value by the comma (,), however, I also want to trim every field before returning the final array, so I did the following:
Arrays.stream(line.split(",")).map(String::trim).toArray();
However, this returns an Object[] array rather than a String[] array. Upon further inspection, I can confirm that the contents are actually String instances, but the array itself is of Object elements. Let me illustrate this, this is what the debugger says of the returned object:
Object[]:
0 = (String) "Key"
1 = (String) "Name"
As far as I can tell, the problem is in the return type of the map call, but how can I make it return a String[] array?
Use toArray(size -> new String[size]) or toArray(String[]::new).
String[] strings = Arrays.stream(line.split(",")).map(String::trim).toArray(String[]::new);
This is actually a lambda expression for
.toArray(new IntFunction<String[]>() {
#Override
public String[] apply(int size) {
return new String[size];
}
});
Where you are telling convert the array to a String array of same size.
From the docs
The generator function takes an integer, which is the size of the desired array, and produces an array of the desired size. This can be concisely expressed with an array constructor reference:
Person[] men = people.stream()
.filter(p -> p.getGender() == MALE)
.toArray(Person[]::new);
Type Parameters:
A - the element type of the resulting array
Parameters:
generator - a function which produces a new array of the desired type and the provided length
String[]::new is a function that invokes the new "pseudo-method" for the String[] type just like String::trim is a function that invokes the real trim method of the String type. The value passed to the String::new function by toArray is the size of the collection on the right-hand side of the .toArray() method invocation.
If you replaced String[]::new with n->new String[n] you might be more comfortable with the syntax just like you could replace String::trim with the less cool s->s.trim()
I have an Array of primitives, for example for int, int[] foo. It might be a small sized one, or not.
int foo[] = {1,2,3,4,5,6,7,8,9,0};
What is the best way to create an Iterable<Integer> from it?
Iterable<Integer> fooBar = convert(foo);
Notes:
Please do not answer using loops (unless you can give a good explanation on how the compiler do something smart about them?)
Also note that
int a[] = {1,2,3};
List<Integer> l = Arrays.asList(a);
Will not even compile
Type mismatch: cannot convert from List<int[]> to List<Integer>
Also check
Why is an array not assignable to Iterable?
before answering.
Also, if you use some library (e.g., Guava), please explain why this is the Best. ( Because its from Google is not a complete answer :P )
Last, since there seems to be a homework about that, avoid posting homeworkish code.
Integer foo[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
List<Integer> list = Arrays.asList(foo);
// or
Iterable<Integer> iterable = Arrays.asList(foo);
Though you need to use an Integer array (not an int array) for this to work.
For primitives, you can use guava:
Iterable<Integer> fooBar = Ints.asList(foo);
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>15.0</version>
<type>jar</type>
</dependency>
For Java8 with lambdas: (Inspired by Jin Kwon's answer)
final int[] arr = { 1, 2, 3 };
final Iterable<Integer> i1 = () -> Arrays.stream(arr).iterator();
final Iterable<Integer> i2 = () -> IntStream.of(arr).iterator();
final Iterable<Integer> i3 = () -> IntStream.of(arr).boxed().iterator();
just my 2 cents:
final int a[] = {1,2,3};
java.lang.Iterable<Integer> aIterable=new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private int pos=0;
public boolean hasNext() {
return a.length>pos;
}
public Integer next() {
return a[pos++];
}
public void remove() {
throw new UnsupportedOperationException("Cannot remove an element of an array.");
}
};
}
};
With Java 8, you can do this.
final int[] arr = {1, 2, 3};
final PrimitiveIterator.OfInt i1 = Arrays.stream(arr).iterator();
final PrimitiveIterator.OfInt i2 = IntStream.of(arr).iterator();
final Iterator<Integer> i3 = IntStream.of(arr).boxed().iterator();
Guava provides the adapter you want as Int.asList(). There is an equivalent for each primitive type in the associated class, e.g., Booleans for boolean, etc.
int foo[] = {1,2,3,4,5,6,7,8,9,0};
Iterable<Integer> fooBar = Ints.asList(foo);
for(Integer i : fooBar) {
System.out.println(i);
}
The suggestions above to use Arrays.asList won't work, even if they compile because you get an Iterator<int[]> rather than Iterator<Integer>. What happens is that rather than creating a list backed by your array, you created a 1-element list of arrays, containing your array.
In Java 8 or later, Iterable is a functional interface returns Iterator.
So you can do this.
static Iterable<Integer> convert(int[] array) {
return () -> Arrays.stream(array).iterator();
}
and
int[] array = {1, 2, 3};
Iterable<Integer> iterable = convert(array);
for (int i : iterable)
System.out.println(i);
output:
1
2
3
I had the same problem and solved it like this:
final YourType[] yourArray = ...;
return new Iterable<YourType>() {
public Iterator<YourType> iterator() {
return Iterators.forArray(yourArray); // Iterators is a Google guava utility
}
}
The iterator itself is a lazy UnmodifiableIterator but that's exactly what I needed.
First of all, I can only agree that Arrays.asList(T...) is clearly the best solution for Wrapper types or arrays with non-primtive datatypes. This method calls a constructor of a simple private static AbstractList implementation in the Arrays class which basically saves the given array reference as field and simulates a list by overriding the needed methods.
If you can choose between a primtive type or a Wrapper type for your array, I would use the Wrapper type for such situations but of course, it's not always useful or required.
There would be only two possibilities you can do:
1) You can create a class with a static method for each primitive datatype array (boolean, byte, short, int, long, char, float, double returning an Iterable<WrapperType>. These methods would use anonymous classes of Iterator (besides Iterable) which are allowed to contain the reference of the comprising method's argument (for example an int[]) as field in order to implement the methods.
-> This approach is performant and saves you memory (except for the memory of the newly created methods, even though, using Arrays.asList() would take memory in the same way)
2) Since arrays don't have methods (as to be read on the side you linked) they can't provide an Iterator instance either. If you really are too lazy to write new classes, you must use an instance of an already existing class that implements Iterable because there is no other way around than instantiating Iterable or a subtype.
The ONLY way to create an existing Collection derivative implementing Iterable is to use a loop (except you use anonymous classes as described above) or you instantiate an Iterable implementing class whose constructor allows a primtive type array (because Object[] doesn't allow arrays with primitive type elements) but as far as I know, the Java API doesn't feature a class like that.The reason for the loop can be explained easily:for each Collection you need Objects and primtive datatypes aren't objects. Objects are much bigger than primitive types so that they require additional data which must be generated for each element of the primitive type array. That means if two ways of three (using Arrays.asList(T...) or using an existing Collection) require an aggregate of objects, you need to create for each primitive value of your int[] array the wrapper object. The third way would use the array as is and use it in an anonymous class as I think it's preferable due to fast performance.
There is also a third strategy using an Object as argument for the method where you want to use the array or Iterable and it would require type checks to figure out which type the argument has, however I wouldn't recommend it at all as you usually need to consider that the Object hasn't always the required type and that you need seperate code for certain cases.
In conclusion, it's the fault of Java's problematic Generic Type system which doesn't allow to use primitive types as generic type which would save a lot of code by using simply Arrays.asList(T...). So you need to program for each primitive type array, you need, such a method (which basically makes no difference to the memory used by a C++ program which would create for each used type argument a seperate method.
You can use IterableOf from Cactoos:
Iterable<String> names = new IterableOf<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
);
Then, you can turn it into a list using ListOf:
List<String> names = new ListOf<>(
new IterableOf<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
)
);
Or simply this:
List<String> names = new ListOf<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
);
While a similar answer has already been sort of posted, I think the reason to use the new PrimitiveIterator.OfInt was not clear. A good solution is to use Java 8 PrimitiveIterator since it's specialized for primitive int types (and avoids the extra boxing/unboxing penalty):
int[] arr = {1,2,3};
// If you use Iterator<Integer> here as type then you can't get the actual benefit of being able to use nextInt() later
PrimitiveIterator.OfInt iterator = Arrays.stream(arr).iterator();
while (iterator.hasNext()) {
System.out.println(iterator.nextInt());
// Use nextInt() instead of next() here to avoid extra boxing penalty
}
Ref: https://doc.bccnsoft.com/docs/jdk8u12-docs/api/java/util/PrimitiveIterator.OfInt.html
In java8 IntSteam stream can be boxed to stream of Integers.
public static Iterable<Integer> toIterable(int[] ints) {
return IntStream.of(ints).boxed().collect(Collectors.toList());
}
I think performance matters based on the size of the array.
So there's Arrays.asList(T... a) but this works on varargs.
What if I already have the array in a T[] a? Is there a convenience method to create a List<T> out of this, or do I have to do it manually as:
static public <T> List<T> arrayAsList(T[] a)
{
List<T> result = new ArrayList<T>(a.length);
for (T t : a)
result.add(t);
return result;
}
Just because it works with varargs doesn't mean you can't call it normally:
String[] x = { "a", "b", "c" };
List<String> list = Arrays.asList(x);
The only tricky bit is if T is Object, where you should use a cast to tell the compiler whether it should wrap the argument in an array or not:
Object[] x = ...;
List<Object> list = Arrays.asList((Object[]) x);
or
Object[] x = ...;
List<Object[]> list = Arrays.asList((Object) x);
As you probably already know, there is a Static class called java.util.Collections which has a number of useful methods for dealing wit arrays such as searching and sorting.
As for your question, the Collection interface specifies methods to add, remove and toArray, amongst others. For one reason or another, the API's authors decided that the add and addAll method will be the only input functions provided to the user.
One explanation for why Java Lists cannot add arrays of objects is that Lists use an iterator and iterators are more strict in their scrolling (i.e. going to the next value) than Arrays which do not have to have all their index values i=(1, 2, 5, 9, 22, ...).
Also, Arrays are not type safe; that is, they cannot guarantee that all their elements conform to a specific super-class or interface, whereas generics (of which List is a member) can guarantee type safety. Hence, the list has the chance to validate each item using the add method.
I think that you can rest assure that your method of adding an array to a list is one of the most (if not most) efficient way of achieving this effect in Java.
I have a hashMap. Each "Value"is going to be a a list which will be mapped later on with my "Key"s. List is desired to look like this:
[length,time][length,time][length,time]
For example:
Key{srcAddr=x, dstAddr=y, srcPort=12345, dstPort=80}
value{(6523,0.001),(124,0.05), () , (), ...}
I just wonder how can I have a two-col arrayList.
package myclassifier;
import java.util.ArrayList;
public class FlowStatics {
int packetLength;
double timeArrival;
public FlowStatics(int pLength, double tArrival)
{
this.packetLength = pLength;
this.timeArrival = tArrival;
}
}
and here is how I used it:
final ArrayList<FlowStatics> staticsArray = new ArrayList<FlowStatics>();
final HashMap<Flows, ArrayList> myHashMap = new HashMap<Flows, ArrayList>();
FlowStatics flowStatics = new FlowStatics(packetLength,timeArrival);
staticsArray.add(flowStatics);
myHashMap.put(flows, staticsArray);
and here is the part that I am reading it:
Iterator<Flows> iterator = myHashMap.keySet().iterator();
while(iterator.hasNext()){
Flows key = iterator.next();
ArrayList value = myHashMap.get(key);
System.out.println("Fows"+key+"----------"+"Statics"+ value);
Well, your FlowStatics is the correct solution
List<FlowStatics> will give you the "two-column array list".
Update: as of your update, myHashMap.put(flows, flowStatics); is wrong. You are this putting an individual pair, rather than a list in the map. You should use:
staticsArray.add(flowStatics);
myHashMap.put(flows, staticsArray);
A List<E> is an abstraction for a homogeneous list of elements whose type is E. There are some restrictions (e.g. no primitives), but conceptually the type E can be defined to be whatever you want.
Suppose there's an abstraction of Pair<L,R>. Then a List<Pair<L,R>> is still a list of some E, but now that E is a Pair<L,R>. So it's still a "one-column" list, but each element in the list is a "pair", so it's sort of a "two-column" list.
Note that you don't always need a generic Pair<L,R>. Any type E that properly encapsulates all the information can be used in a List<E>.
And by the way, you can have a List<List<E>> too.
See also
Wikipedia/Encapsulation
Related questions
What is the equivalent of the C++ Pair<L,R> in Java?
List of Lists of Lists
Returning values analogy
Often people ask "How can I return two values in Java?". The answer is analogous. You return one value, a new type which encapsulates both information.
So instead of:
// attempt to return two values
// DOES NOT COMPILE
return "James Bond";
return "007";
You do:
return new SecretAgent("James Bond", "007");
Related questions
Using a java method to return multiple values?