Reputation: 1633
I have 2 questions about arrays in java
and any help would be appreciated.
Is there a way to access a sub-array (something like this on python: array[1:5]
)
I want to know does java
has a function that counts a specific element in an array
or not.
I don't want to use for loops.
Upvotes: 2
Views: 12324
Reputation: 3433
The Java 8 way of doing this will be:
Arrays.stream(array, 1, 5)
Arrays.stream(array).filter(x -> x == element).count()
where array
is your input int[]
and element
is the integer item to be counted
Explanation:
Arrays.stream(array, 1, 5)
will return you a Stream
object containing elements present in the array
from index 1 to 4. That Stream
can be further converted to int[]
if needed using toArray()
or can be directly used if some aggregate function is required on it like min()
Arrays.stream(array).filter(x -> x == element).count()
will first convert the given array
to Stream
and then will apply the filter()
filtering out any element that doesn't match the boolean condition specified and then will return the count()
of the filtered in element.Note: This or any other method for counting the number of occurrences of an item in an array will internally have to loop though the elements.
Upvotes: 2
Reputation: 929
For your first question, you can use copyOfRange
static method of Arrays
class.
Example use:
int[] array = new int[]{1, 2, 3, 4, 5};
int[] subArray = Arrays.copyOfRange(array, 1, 3);
//subArray = [2, 3]
And for your second question, that method has to traverse whole array and that cannot be done without a loop.
Upvotes: 6
Reputation: 1502306
For accessing part of an array, you could use Arrays.asList
to obtain a List<E>
, and then use the subList
method to obtain a slice:
import java.util.*;
public class Test {
public static void main(String[] args) {
String[] array = { "zero", "one", "two", "three", "four", "five", "six" };
List<String> list = Arrays.asList(array);
List<String> sublist = list.subList(1, 5);
for (String item : sublist) {
System.out.println(item);
}
}
}
Output:
one
two
three
four
For your second question: even if such a method existed, it would have to loop. I'm not aware of any such method in the standard libraries, so I suggest you write your own using a loop.
Upvotes: 4