Amen
Amen

Reputation: 1633

Accessing sub-array and counting an element in arrays in Java

I have 2 questions about arrays in java and any help would be appreciated.

  1. Is there a way to access a sub-array (something like this on python: array[1:5])

  2. 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

Answers (3)

Vikas Prasad
Vikas Prasad

Reputation: 3433

The Java 8 way of doing this will be:

  1. Arrays.stream(array, 1, 5)
  2. Arrays.stream(array).filter(x -> x == element).count()

where array is your input int[] and element is the integer item to be counted

Explanation:

  1. 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()
  2. 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

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

Jon Skeet
Jon Skeet

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

Related Questions