So, the task was to expand the functionality of the ArrayList in order to teach it to find an element by a predicate (yes, hello C #). But as luck would have it, by queries, Google only issues "New features in java 7 \ 8", etc. I ask you to leave information about the subject, or give a specific version of such an implementation (a function with an argument and an explanation of how this function will dynamically receive T from the sheet object).
- Those. Should a function accept an array element and return a boolean? - Anton Shchyrov
|
3 answers
Well, if the 8th java, then there is the predicate itself as such. Create a stream from the list, filter it with a predicate , and form the result in the list.
List<String> lines = Arrays.asList("one", "two", "one", "two"); List<String> result = lines.stream() .filter(line -> !"one".equals(line)) .collect(Collectors.toList()); Here still primerchik is.
|
Your method must accept one of the functional interfaces. Those. an interface in which there is exactly one non-static method.
A list of standard functional interfaces can be found here.
You need an interface Predicate<T> . It has a test(T t) method test(T t) which takes an object of a parameterized type T and returns a boolean .
The full code is
class CustomArrayList<T> extends ArrayList<T> { public int customIndexOf(Predicate<T> pred) { for (int i = 0; i < size(); i++) { if (pred.test(get(i)) // Проверяем, наш ли элемент? return i; } return -1; } } And use
CustomArrayList<Integer> list = new CustomArrayList<>(); ........ int idx = list.customIndexOf((val) -> val % 5 == 0); Find the first item dividing by 5
|
class MyArrayList<E> extends ArrayList<E> { public Optional<E> findFirst(Predicate<E> predicate) { for (E item : this) { if (predicate.test(item)) return Optional.of(item); } return Optional.empty(); } } MyArrayList<Integer> list = new MyArrayList<>(); list.add(1); list.add(2); list.add(3); Optional<Integer> item = list.findFirst(i -> i == 2); |