How to collect a string to a stack of characters in Java 8? [duplicate] - string

I would like to convert the string containing abc to a list of characters and a hashset of characters. How can I do that in Java ?
List<Character> charList = new ArrayList<Character>("abc".toCharArray());

In Java8 you can use streams I suppose.
List of Character objects:
List<Character> chars = str.chars()
.mapToObj(e->(char)e).collect(Collectors.toList());
And set could be obtained in a similar way:
Set<Character> charsSet = str.chars()
.mapToObj(e->(char)e).collect(Collectors.toSet());

You will have to either use a loop, or create a collection wrapper like Arrays.asList which works on primitive char arrays (or directly on strings).
List<Character> list = new ArrayList<Character>();
Set<Character> unique = new HashSet<Character>();
for(char c : "abc".toCharArray()) {
list.add(c);
unique.add(c);
}
Here is an Arrays.asList like wrapper for strings:
public List<Character> asList(final String string) {
return new AbstractList<Character>() {
public int size() { return string.length(); }
public Character get(int index) { return string.charAt(index); }
};
}
This one is an immutable list, though. If you want a mutable list, use this with a char[]:
public List<Character> asList(final char[] string) {
return new AbstractList<Character>() {
public int size() { return string.length; }
public Character get(int index) { return string[index]; }
public Character set(int index, Character newVal) {
char old = string[index];
string[index] = newVal;
return old;
}
};
}
Analogous to this you can implement this for the other primitive types.
Note that using this normally is not recommended, since for every access you
would do a boxing and unboxing operation.
The Guava library contains similar List wrapper methods for several primitive array classes, like Chars.asList, and a wrapper for String in Lists.charactersOf(String).

The lack of a good way to convert between a primitive array and a collection of its corresponding wrapper type is solved by some third party libraries. Guava, a very common one, has a convenience method to do the conversion:
List<Character> characterList = Chars.asList("abc".toCharArray());
Set<Character> characterSet = new HashSet<Character>(characterList);

Use a Java 8 Stream.
myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
Breakdown:
myString
.chars() // Convert to an IntStream
.mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
.collect(Collectors.toList()); // Collect in a List<Character>
(I have absolutely no idea why String#chars() returns an IntStream.)

The most straightforward way is to use a for loop to add elements to a new List:
String abc = "abc";
List<Character> charList = new ArrayList<Character>();
for (char c : abc.toCharArray()) {
charList.add(c);
}
Similarly, for a Set:
String abc = "abc";
Set<Character> charSet = new HashSet<Character>();
for (char c : abc.toCharArray()) {
charSet.add(c);
}

List<String> result = Arrays.asList("abc".split(""));

Create an empty list of Character and then make a loop to get every character from the array and put them in the list one by one.
List<Character> characterList = new ArrayList<Character>();
char arrayChar[] = abc.toCharArray();
for (char aChar : arrayChar)
{
characterList.add(aChar); // autoboxing
}

You can do this without boxing if you use Eclipse Collections:
CharAdapter abc = Strings.asChars("abc");
CharList list = abc.toList();
CharSet set = abc.toSet();
CharBag bag = abc.toBag();
Because CharAdapter is an ImmutableCharList, calling collect on it will return an ImmutableList.
ImmutableList<Character> immutableList = abc.collect(Character::valueOf);
If you want to return a boxed List, Set or Bag of Character, the following will work:
LazyIterable<Character> lazyIterable = abc.asLazy().collect(Character::valueOf);
List<Character> list = lazyIterable.toList();
Set<Character> set = lazyIterable.toSet();
Bag<Character> set = lazyIterable.toBag();
Note: I am a committer for Eclipse Collections.

IntStream can be used to access each character and add them to the list.
String str = "abc";
List<Character> charList = new ArrayList<>();
IntStream.range(0,str.length()).forEach(i -> charList.add(str.charAt(i)));

Using Java 8 - Stream Funtion:
Converting A String into Character List:
ArrayList<Character> characterList = givenStringVariable
.chars()
.mapToObj(c-> (char)c)
.collect(collectors.toList());
Converting A Character List into String:
String givenStringVariable = characterList
.stream()
.map(String::valueOf)
.collect(Collectors.joining())

To get a list of Characters / Strings -
List<String> stringsOfCharacters = string.chars().
mapToObj(i -> (char)i).
map(c -> c.toString()).
collect(Collectors.toList());

Related

How to write String Iteration with Map Put operations in Java 8?

I am trying to convert following code into Java 8::
String s = "12345";
Map<Character,Integer> map = new HashMap<Character,Integer>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
int cnt = map.get(c);
map.put(c, ++cnt);
} else {
map.put(c, 1);
}
}
I tried and found following way to iterate:
IntStream.rangeClosed(0, s.length).foreach(d -> {
//all statements from char to map.put
}) ;
I am not sure whether this is correct way to do it.
You can do this:
s.chars()
.mapToObj(x -> (char) x)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
.mapToObj(x -> (char) x) is necessary because .chars() gives you a stream of ints, but in order to use groupingBy you need to work with objects, not primitives
groupingBy receives a function to get the key to group by and a Collector implementation
Function.identity() is just a function that returns whatever element it is passed to it
Collectors.counting() is a collector that counts
You can use the groupingBy() and counting() collectors:
String s = "12345";
Map<Character, Long> map = s
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(map);
Unfortunately, there seems to be no convenient way to get a Stream<Character> from a string, hence the need to map to an IntStream using chars() and then using mapToObj() to convert it to a character stream.

How to concatenate two string in Dart?

I am new to Dart programming language and anyone help me find the best string concatenation methods available in Dart.
I only found the plus (+) operator to concatenate strings like other programming languages.
There are 3 ways to concatenate strings
String a = 'a';
String b = 'b';
var c1 = a + b; // + operator
var c2 = '$a$b'; // string interpolation
var c3 = 'a' 'b'; // string literals separated only by whitespace are concatenated automatically
var c4 = 'abcdefgh abcdefgh abcdefgh abcdefgh'
'abcdefgh abcdefgh abcdefgh abcdefgh';
Usually string interpolation is preferred over the + operator.
There is also StringBuffer for more complex and performant string building.
If you need looping for concatenation, I have this :
var list = ['satu','dua','tiga'];
var kontan = StringBuffer();
list.forEach((item){
kontan.writeln(item);
});
konten = kontan.toString();
Suppose you have a Person class like.
class Person {
String name;
int age;
Person({String name, int age}) {
this.name = name;
this.age = age;
}
}
And you want to print the description of person.
var person = Person(name: 'Yogendra', age: 29);
Here you can concatenate string like this
var personInfoString = '${person.name} is ${person.age} years old.';
print(personInfoString);
Easiest way
String get fullname {
var list = [firstName, lastName];
list.removeWhere((v) => v == null);
return list.join(" ");
}
The answer by Günter covers the majority of the cases of how you would concatenate two strings in Dart.
If you have an Iterable of Strings it will be easier to use writeAll as this gives you the option to specify an optional separator
final list = <String>['first','second','third'];
final sb = StringBuffer();
sb.writeAll(list, ', ');
print(sb.toString());
This will return
'first, second, third'
Let's think we have two strings
String a = 'Hello';
String b = 'World';
String output;
Now we want to concat this two strings
output = a + b;
print(output);
Hello World

String Tokenizer requiremen

String str= -PT31121936-1-0069902679870--BLUECH
I want divide the above string by useing string Tokenize
output like this:
amount=" ";
txnNo = PT31121936;
SeqNo = 1;
AccNo = 0069902679870;
Cldflag=" ";
FundOption= BLUECH;
Solution in Java using String split, it would be better than String tokenizer.
There are two solutions
1) This approach is assuming the input string will be always in a specific order.
2) This approach is more dynamic, where we can accommodate change in the order of the input string and also in the number of parameters. My preference would be the second approach.
public class StringSplitExample {
public static void main(String[] args) {
// This solution is based on the order of the input
// is Amount-Txn No-Seq No-Acc No-Cld Flag-Fund Option
String str= "-PT31121936-1-0069902679870--BLUECH";
String[] tokens = str.split("-");
System.out.println("Amount :: "+tokens[0]);
System.out.println("Txn No :: "+tokens[1]);
System.out.println("Seq No :: "+tokens[2]);
System.out.println("Acc No :: "+tokens[3]);
System.out.println("Cld Flag :: "+tokens[4]);
System.out.println("Fund Option :: "+tokens[5]);
// End of First Solution
// The below solution can take any order of input, but we need to provide the order of input
String[] tokensOrder = {"Txn No", "Amount", "Seq No", "Cld Flag", "Acc No", "Fund Option"};
String inputString = "PT31121936--1--0069902679870-BLUECH";
String[] newTokens = inputString.split("-");
// Check whether both arrays are having equal count - To avoid index out of bounds exception
if(newTokens.length == tokensOrder.length) {
for(int i=0; i<tokensOrder.length; i++) {
System.out.println(tokensOrder[i]+" :: "+newTokens[i]);
}
}
}
}
Reference: String Tokenizer vs String split
Scanner vs. StringTokenizer vs. String.Split

How to Convert an ArrayList to string C#

ArrayList arr = new ArrayList();
string abc =
What should I do to convert arraylist to a string such as abc = arr;Updated QuestOther consideration from which i can complete my work is concatination of string(need help in that manner ). suppose i have a string s="abcdefghi.."by applying foreach loop on it and getting char by matching some condition and concatinating every char value in some insatnce variable of string type i.e string subString=+;Something like thisstring tem = string.Empty;
string temp =string.Empty;
temp = string.Concat(tem,temp);
Using a little linq and making the assumption that your ArrayList contains string types:
using System.Linq;
var strings = new ArrayList().Cast<string>().ToArray();
var theString = string.Join(" ", strings);
Further reading:
http://msdn.microsoft.com/en-us/library/57a79xd0.aspx
For converting other types to string:
var strings = from object o in myArrayList
select o.ToString();
var theString = string.Join(" ", strings.ToArray());
The first argument to the Join method is the separator, I chose whitespace. It sounds like your chars should all contribute without a separator, so use "" or string.Empty instead.
Update: if you want to concatenate a small number of strings, the += operator will suffice:
var myString = "a";
myString += "b"; // Will equal "ab";
However, if you are planning on concatenating an indeterminate number of strings in a tight loop, use the StringBuilder:
using System.Text;
var sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
sb.Append("a");
}
var myString = sb.ToString();
This avoids the cost of lots of string creations due to the immutability of strings.
Look into string.Join(), the opposite of string.Split()
You'll also need to convert your arr to string[], I guess that ToArray() will help you do that.
Personally and for memory preservation I’ll do for a concatenation:
System.Collections.ArrayList Collect = new System.Collections.ArrayList();
string temporary = string.Empty;
Collect.Add("Entry1");
Collect.Add("Entry2");
Collect.Add("Entry3");
foreach (String var in Collect)
{
temporary = temporary + var.ToString();
}
textBox1.Text = temporary;

How to truncate a string in groovy?

How to truncate string in groovy?
I used:
def c = truncate("abscd adfa dasfds ghisgirs fsdfgf", 10)
but getting error.
The Groovy community has added a take() method which can be used for easy and safe string truncation.
Examples:
"abscd adfa dasfds ghisgirs fsdfgf".take(10) //"abscd adfa"
"It's groovy, man".take(4) //"It's"
"It's groovy, man".take(10000) //"It's groovy, man" (no exception thrown)
There's also a corresponding drop() method:
"It's groovy, man".drop(15) //"n"
"It's groovy, man".drop(5).take(6) //"groovy"
Both take() and drop() are relative to the start of the string, as in "take from the front" and "drop from the front".
Online Groovy console to run the examples:
https://ideone.com/zQD9Om — (note: the UI is really bad)
For additional information, see "Add a take method to Collections, Iterators, Arrays":
https://issues.apache.org/jira/browse/GROOVY-4865
In Groovy, strings can be considered as ranges of characters. As a consequence, you can simply use range indexing features of Groovy and do myString[startIndex..endIndex].
As an example,
"012345678901234567890123456789"[0..10]
outputs
"0123456789"
we can simply use range indexing features of Groovy and do someString[startIndex..endIndex].
For example:
def str = "abcdefgh"
def outputTrunc = str[2..5]
print outputTrunc
Console:
"cde"
To avoid word break you can make use of the java.text.BreakIterator. This will truncate a string to the closest word boundary after a number of characters.
Example
package com.example
import java.text.BreakIterator
class exampleClass {
private truncate( String content, int contentLength ) {
def result
//Is content > than the contentLength?
if(content.size() > contentLength) {
BreakIterator bi = BreakIterator.getWordInstance()
bi.setText(content);
def first_after = bi.following(contentLength)
//Truncate
result = content.substring(0, first_after) + "..."
} else {
result = content
}
return result
}
}
Here's my helper functions to to solve this kinda problem. In many cases you'll probably want to truncate by-word rather than by-characters so I pasted the function for that as well.
public static String truncate(String self, int limit) {
if (limit >= self.length())
return self;
return self.substring(0, limit);
}
public static String truncate(String self, int hardLimit, String nonWordPattern) {
if (hardLimit >= self.length())
return self;
int softLimit = 0;
Matcher matcher = compile(nonWordPattern, CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS).matcher(self);
while (matcher.find()) {
if (matcher.start() > hardLimit)
break;
softLimit = matcher.start();
}
return truncate(self, softLimit);
}

Resources