Reputation: 1133
Is it possible to create a sublist from another list, using only the element indices? I'm looking for nice solution e.g. lambdas, streams from Java 8.
For example (pseudocode):
a = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
b = a.getByIndices([0, 2, 4, 5, 3])
print(b) // [10, 8, 6, 5, 7]
Upvotes: 4
Views: 2071
Reputation: 328735
For arrays of ints you could use this:
int[] b = IntStream.of(0, 2, 4, 5, 3)
.map(i -> a[i])
.toArray();
Upvotes: 6
Reputation: 36
I wrote this function that does what you ask. I can't figure out how to make it lambda function but I'll keep working on it.
public static <E> void createSublist(List<E> oldList, List<E> newList, int[] indicies){
for(int i = 0; i < indicies.length; i++)
newList.add(oldList.get(indicies[i]));} //Adds indicies to new list
Upvotes: 0
Reputation: 50041
Extending AbstractList
is a quick way to get a list implementation up and running. Like the regular List.subList
method, the following sublist is backed by the main list, so changes to the sublist will write through to the main list (which may or may not be a feature you wanted, but you can always create a new, separate ArrayList from the sublist if needed). Element removal through the sublist is not implemented; it would be doable but require a bit more work.
public static <E> List<E> sublistFromIndices(List<E> list, int... indices) {
Objects.requireNonNull(list);
Objects.requireNonNull(indices);
return new AbstractList<E>() {
@Override
public int size() {
return indices.length;
}
@Override
public E get(int index) {
return list.get(indices[index]);
}
@Override
public E set(int index, E element) {
return list.set(indices[index], element);
}
};
}
Upvotes: 2
Reputation: 137184
You could have the following method:
private static <T> List<T> getByIndices(List<T> list, List<Integer> indexes) {
return indexes.stream().map(list::get).collect(toList());
}
This creates a Stream
from the given indexes, maps to the element of the list at the index and collect the result to a list.
Sample usage:
List<Integer> list = Arrays.asList(10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
List<Integer> indexes = Arrays.asList(0, 2, 4, 5, 3);
System.out.println(getByIndices(list, indexes)); // prints [10, 8, 7, 6, 5]
Upvotes: 10