c# 4.0 - Java Streams v .Net (C#) LINQ -
i need know if string or char array has duplicate characters , if how many of each duplicates there are.
with linq can following way:-
class program { private const string source = "appearances"; static void main(string[] args) { var testq = ch in source group ch ch testg testg.count<char>() > 1 select testg; int num; foreach (var tg in testq) { num = tg.count(); console.out.writeline("{0}, {1}", tg.elementat(0), num); } console.readline(); } } can suggest how might go java streams?
you stream - suppose mean java 8.
here how it:
public map<character, integer> countoccurs(final char[] input) { return countoccurs(new string(input)); } public map<character, integer> countoccurs(final string input) { return input.chars(). collect( hashmap::new, (m, c) -> m.merge((char) c, 1, integer::sum), hashmap::putall ); } the idea take intstream of char values in string int. collect() intstream map; foldleft operation functional language. map.merge method takes key , value , lambda merges existing value , new value if 1 in map - pass integer::sum add 2 values together.
the gymnastics int , char , character legacy java issue. there no primitive charstream in new java 8 api have use intstream - have cast int char , autoboxed character.
example usage:
system.out.println(countoccurs("abbccddde")); output:
{a=1, b=2, c=2, d=3, e=1} if want filter counts can do:
final map<character, integer> count = countoccurs("abbccddde"); count.entryset().stream(). filter(e -> e.getvalue() > 1). foreach(system.out::println); which give you:
b=2 c=2 d=3 if want similar in logic linq example, would work:
public collection<? extends map.entry<character, integer>> countoccurs(final string input) { return input.chars().boxed(). collect(groupingby(identity())).entryset().stream(). filter(e -> e.getvalue().size() > 1). map(e -> new abstractmap.simpleentry<>((char)(int)e.getkey(), e.getvalue().size())). collect(tolist()); } but it's quite ugly , requires intermediate collection.
p.s. excuse formatting, i'm not yet sure how format long lines of stream manipulation. i'm sure there'll style guidelines established soon.
Comments
Post a Comment