Convert String to ArrayList<Character>, without Regex - java

Is there anyway to convert a String to an ArrayList<Character> without using regex.
For example:
"abc".methodHere == ArrayList<Character>["a", "b", "c"]
This link converts a String to an ArrayList<String> and this link uses Array and not ArrayList

You could get the stream of characters and collect to a list:
List<Character> chars = s.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.toList());
If you want an ArrayList specifically, you could collect to an ArrayList:
List<Character> chars = s.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.toCollection(ArrayList::new));

Iterate through the characters in the string by index
ArrayList<Character> chars = new ArrayList<>();
for (int i = 0; i < str.length(); i++)
chars.add(str.charAt(i));
// do whatever with the chars list

Alternatively, you can do
ArrayList<Character> chars =
new ArrayList<>(Chars.asList(string.toCharArray()));
You need to import com.google.common.primitives.Chars; from Guava library.

A different answer from the ones already provided:
ArrayList<Character> list = (ArrayList<Character>)"abc".chars().mapToObj(i -> (char)i).collect(Collectors.toList());

Related

How should I map a function onto a string array in java?

I want to split a string and trim each word in the newly established array. Is there a simple (functional) way in Java how to do it as a one liner without the use of a cycle?
String[] stringarray = inputstring.split(";");
for (int i = 0; i < stringarray.length; i++) {
stringarray[i] = stringarray[i].trim();
}
EDIT: corrected the cycle (Andreas' comment)
You can do it in the following way:
String[] stringarray = inputstring.trim().split("\\s*;\\s*");
Explanation of the regex:
\s* is zero or more times whitespace
\s*;\s* specifies zero or more times whitespace followed by ; which may be followed by zero or more times whitespace
With streams you could do this:
String[] stringarray = Arrays.stream(inputstring.split(";"))
.map(String::trim)
.toArray(String[]::new);
This may not be pure Array solution but a java 8 solution:
String str = " string1 ;string2 ;string3 ;string4;";
String [] s = Arrays.stream(str.split(";")).map(String::trim).collect(Collectors.toList()).toArray(new String[]{});
System.out.println(Arrays.toString(s));
First convert the array to a stream (using the Arrays class), then use the map function, then convert back to array.
https://mkyong.com/java8/java-8-how-to-convert-a-stream-to-array/

Joining two strings with delimiters

I'm trying to join two strings together that have comma delimiters. I want to loop it so that it becomes consecutive, meaning that the first item in string one before the comma is then followed by the first item in string two and so on. Here is the two strings and how I would want them to join.
String 1 = 0,E,EEE,0,0,WWWW,EE,W,EE
String 2 = 0,NNN,N,SS,0,S,N,N,SS
Outcome = 00,ENNN,EEEN,0SS,00,WWWS,EEN,WN,EESS
Is this even possible? I have the code to join the two strings but it doesn't put them in the order I'm needing.
Split one and two by , and then use IntStream to generate the indices of your two token arrays and join the elements by concatenation and then ,. Like,
String a = "0,E,EEE,0,0,WWWW,EE,W,EE", b = "0,NNN,N,SS,0,S,N,N,SS";
String[] aTok = a.split(","), bTok = b.split(",");
String out = IntStream.range(0, Math.min(aTok.length, bTok.length))
.mapToObj(i -> aTok[i] + bTok[i]).collect(Collectors.joining(","));
System.out.println(out);
Outputs (as requested)
00,ENNN,EEEN,0SS,00,WWWWS,EEN,WN,EESS
Split each string into a string array,
concatenate the items of the same index in both tables and append a , after each pair:
String s1 = "0,E,EEE,0,0,WWWW,EE,W,EE";
String s2 = "0,NNN,N,SS,0,S,N,N,SS";
String[] tokens1 = s1.split(",");
String[] tokens2 = s2.split(",");
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < tokens1.length; i++) {
sb.append(tokens1[i]).append(tokens2[i]).append(",");
}
sb.deleteCharAt(sb.length() - 1); // remove the last ","
String result = sb.toString();
System.out.println(result);
Of course this works only if the 2 strings can be split in the same number of items.

How to count occurrence of each character in java string using Pattern Class(Regex)

I am trying to find a number of Occurrence of each character on the given string.
Expected output: t=2 e=1 s=1 i=1 n=1 g=1
Current output:T=0 e=0 s=0 t=0 i=0 n=0 g=0
Code:
String str = "Testing";
int count = 0;
Pattern p = Pattern.compile("[a-zA-Z]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
while (m.find()) {
if (m.group().equals(str)) {
count++;
}
System.out.println(m.group() + "=" + count);
}
There are many ways of doing this but I am looking for Regex only, so how can we achieve that by using Regex. Any Help would be Appreciated. Thanks in advance.
No need for a regex to solve your problem, if you are using Java8+ you can just use :
String input = "Testing";
Map<String, Long> result = Arrays.stream(input.split(""))
.map(String::toLowerCase)
.collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));
outputs
{t=2, e=1, s=1, i=1, n=1, g=1}
Edit
mmm, Pattern in this case is useless I don't advice to use it in this problem, as an alternative solution using Pattern with results from Java9+ you can use :
String str = "Testing";
Pattern.compile(".").matcher(str)
.results()
.map(m -> m.group().toLowerCase())
.collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()))
.forEach((k, v) -> System.out.println(k + " = " + v));
Outputs
t = 2
e = 1
s = 1
i = 1
n = 1
g = 1
There are a lot of ways of achieving the result, but Regex is not a tool for this one. If you want to filter the characters and assure only [a-zA-Z] will be count, filter the unwanted characters with: string = string.replaceAll("[^a-zA-Z]", "");. Now back to your issue.
You need to split String to characters and a Map<Character, Integer> you will store these characters and their number of occurrences. I suggest you use LinkedHashMap<Character, Integer> which assures the order of the insertion.
char[] charArray = string.toCharArray();
Map<Character, Integer> map = new LinkedHashMap<>();
Now loop through the characters and save them to the map. If a character has already been stored, increment the value by one. This might be achieved with a procedural and traditional for-loop or since Java 8 you can use java-stream.
Before Java 8:
for (char ch: charArray) {
if(map.containsKey(ch)){
map.put(ch, map.get(ch)+1);
} else {
map.put(ch, 1);
}
}
After Java 8 (string.split("") returns an array of Strings, you need to map them to characters):
Map<Character, Long> map = Arrays
.asList(string.split("")).stream().map(s -> s.charAt(0))
.collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));
In both cases the output will be the same:
System.out.println(map); // prints {t=2, e=1, s=1, i=1, n=1, g=1}

Adding alphabets to a Java HashSet

I want to add all lowercase alphabets to a Java HashSet. For this I use the following code snippet:
for(char c = 'a'; c <= 'z'; c++)
set.add(c);
Is there a better way to do this, like one in which I don't have to iterate over all the alphabets?
In Java 8 using IntStream, I think you should be able to get all lowercase Character values like this:
Set<Character> set = IntStream.rangeClosed(Character.MIN_VALUE, Character.MAX_VALUE)
.filter(Character::isLowerCase)
.mapToObj(i -> Character.valueOf((char) i))
.collect(Collectors.toSet());
This Set<Character> contains 1,402 Character objects.
If you don't want to box the char values as Character objects, and don't mind using a third-party library, you can do the following with Eclipse Collections:
CharSet charSet = IntInterval.zeroTo(Character.MAX_VALUE)
.asLazy()
.select(Character::isLowerCase)
.collectChar(i -> (char) i)
.toSet();
This CharSet contains 1,402 char values.
If you don't want ALL lowercase letters, then just change your range to the ones you are looking for. For example:
CharSet charSet = IntInterval.fromTo('a', 'z')
.asLazy()
.collectChar(i -> (char) i)
.toSet();
Note: I am a committer for Eclipse Collections

Converting ArrayList of Characters to a String?

How to convert an ArrayList<Character> to a String in Java?
The List.toString method returns it as [a,b,c] string - I want to get rid of the brackets (etcetera) and store it as abc.
You can iterate through the list and create the string.
String getStringRepresentation(ArrayList<Character> list)
{
StringBuilder builder = new StringBuilder(list.size());
for(Character ch: list)
{
builder.append(ch);
}
return builder.toString();
}
Setting the capacity of the StringBuilder to the list size is an important optimization. If you don't do this, some of the append calls may trigger an internal resize of the builder.
As an aside, toString() returns a human-readable format of the ArrayList's contents. It is not worth the time to filter out the unnecessary characters from it. It's implementation could change tomorrow, and you will have to rewrite your filtering code.
Here a possible one-line solution using Java8 streams.
a) List of Character objects to String :
String str = chars.stream()
.map(e->e.toString())
.reduce((acc, e) -> acc + e)
.get();
b) array of chars (char[] chars)
String str = Stream.of(chars)
.map(e->new String(e))
.reduce((acc, e) -> acc + e)
.get();
UPDATE (following comment below):
a) List of Character objects to String :
String str = chars.stream()
.map(e->e.toString())
.collect(Collectors.joining());
b) array of chars (char[] chars)
String str = Stream.of(chars)
.map(e->new String(e))
.collect(Collectors.joining());
Note that the map(e->e.toString()) step in the above solutions will create a temporary string for each character in the list. The strings immediately become garbage. So, if the performance of the conversion is a relevant concern, you should consider using the StringBuilder approach instead.
How about this, Building the list
List<Character> charsList = new ArrayList<Character>();
charsList.add('h');
charsList.add('e');
charsList.add('l');
charsList.add('l');
charsList.add('o');
Actual code to get String from List of Character:
String word= new String();
for(char c:charsList){
word= word+ c;
}
System.out.println(word);
Still learning if there is a misake point out.
You can do it using toString() and RegExp without any loops and streams:
List<Character> list = Arrays.asList('a', 'b', 'c');
String s = list.toString().replaceAll("[,\\s\\[\\]]", "");
Assuming you have a following list:
final ArrayList<Character> charsList = new ArrayList<Character>();
charsList.add('h');
charsList.add('e');
charsList.add('l');
charsList.add('l');
charsList.add('o');
This will yield hello (I am using org.apache.commons.lang.ArrayUtils helper class):
final Character[] charactersArray =
charsList.toArray(new Character[charsList.size()]);
final char[] charsArray = ArrayUtils.toPrimitive(charactersArray);
System.out.println(String.valueOf(charsArray));
Using join of a Joiner class:
// create character list and initialize
List<Character> arr = Arrays.asList('a', 'b', 'c');
String str = Joiner.on("").join(arr);
System.out.println(str);
Use toString then remove , and spaces
import com.google.common.base.Joiner;
....
<Character> arr = Arrays.asList('h', 'e', 'l', 'l', 'o');
// remove [] and spaces
String str = arr.toString()
.substring(1, 3 * str.size() - 1) //3 bcs of commas ,
.replaceAll(", ", "");
System.out.println(str);
Or by using streams:
import java.util.stream.Collectors;
...
// using collect and joining() method
String str = arr.stream().map(String::valueOf).collect(Collectors.joining());
Easiest is to loop through.
List<String> strings = new ArrayList<String>();
// populate strings
StringBuilder builder = new StringBuilder();
for(String string : strings) {
builder.append(string).append(',');
}
if(builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
System.out.println(builder);
Many solutions available. You can iterate over the chars and append to a StringBuilder, then when finished appending, call .toString on the StringBuilder.
Or use something like commons-lang StringUtils.join from the apache commons-lang project.
a tiny complement to #waggledans 's answer
a) List of Character objects to String :
String str = chars.stream().map(e->e.toString()).collect(Collectors.joining());
which e->e.toString() can be replaced by Object::toString
String str = chars.stream().map(Object::toString).collect(Collectors.joining());
I consider this an easy and smart way
// given list containing the chars
List<Character> arr = Arrays.asList('a', 'b', 'c');
//convert list to string
String output = arr.toString().replaceAll("[ ,]","")
.substring(1, tmpArr.length()-1);
Explanation:
// convert to string.
String str = arr.toString(); // result is "[a ,b ,c]"
// get rid of the start and the end char i.e '[' & ']'
str = str.substring(1, tmpArr.length()-1); //result is "a ,b ,c"
// replace <space> and ','
str = str.replaceAll(" ,","") "ABC"
I would say :
public String arayListToString(ArrayList arrayList){
StringBuffer b = new StringBuffer();
for(String s : arrayList){
b.append(s);
b.append(",");
}
return b.toString();
}
private void countChar() throws IOException {
HashMap hashMap = new HashMap();
List list = new ArrayList();
list = "aammit".chars().mapToObj(r -> (char) r).collect(Collectors.toList());
list.stream().forEach(e -> {
hashMap.computeIfPresent(e, (K, V) -> (int) V + 1);
hashMap.computeIfAbsent(e, (V) -> 1);
});
System.out.println(hashMap);
}

Categories