Answer the question
In order to leave comments, you need to log in
How to work with ArrayList correctly?
Hello. I'm learning Java by solving problems on Codewars.
First, I solve the problem I'm interested in in JavaScript, then in Java, thereby learning methods in Java.
For example:
function findChildren(dancingBrigade) {
return dancingBrigade
.toLowerCase()
.split('')
.sort()
.map((currentValue, index, array) => {
const previousValue = array[index - 1];
if (index === 0 || currentValue !== previousValue) {
return currentValue.toUpperCase();
}
return currentValue;
})
.join('');
}
const s = 'beeeEBb'; // BbbEeee
const s2 = 'uwwWUueEe'; // EeeUuuWww
console.log(findChildren(s)); // beeeEBb
// console.log(findChildren(s2)); // EeeUuuWww
package main.java.kyu6;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class WhereIsMyParent {
static int index = 0;
static String findChildren(final String text) {
ArrayList<Character> arrayList = new ArrayList<>();
for (int i = 0; i < text.length(); i++) {
Character currentValue = Character.toLowerCase(text.charAt(i));
// System.out.println(text.charAt(i));
arrayList.add(currentValue);
}
System.out.println(arrayList);
System.out.println(Collections.sort(arrayList));
List<Character> result = arrayList.stream().map((currentValue) -> {
Character previousValue = arrayList.get(index - 1);
index++;
return currentValue;
}).collect(Collectors.toList());
// System.out.println("result " + result);
return "";
}
public static void main(String[] args) {
String s = "beeeEBb"; // "EeeeBbb"
String s2 = "uwwWUueEe"; // "WwwUuuEee"
System.out.println(findChildren(s)); // "EeeeBbb"
// System.out.println(findChildren(s2)); // "WwwUuuEee"
}
}
System.out.println(Collections.sort(arrayList));
If (currentValue !== previousValue) {}
Character previousValue = arrayList.get(index - 1);
Answer the question
In order to leave comments, you need to log in
0. It's the 21st year in the yard. No need to use old versions of java and declare a type for local variables.
var arrayList = new ArrayList<Character>>();
1. To make an array out of a string, use the .split function: var array = someString.toLowerCase().split("")
2. System.out.println(Collections.sort(arrayList));
.sort is void. It doesn't return anything. Here you will have a compilation error.
3.
{
Character previousValue = arrayList.get(index - 1);
index++;
return currentValue;
}
no one does that at all. The main problem is the use of global variables inside the lambda. Consider that there is no way you can get previousValue (not in StreamAPI). Come up with another solution.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question