Mapping a stream of tokens to a stream of n-grams in Java 8 -


i think basic question concerning java 8 streams, have difficult time thinking of right search terms. asking here. getting java 8, bear me.

i wondering how map stream of tokens stream of n-grams (represented arrays of tokens of size n). suppose n = 3, convert following stream

{1, 2, 3, 4, 5, 6, 7} 

to

{[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]} 

how accomplish java 8 streams? should possible compute concurrently, why interested in accomplishing streams (it doesn't matter in order n-arrays processed).

sure, old-fashioned for-loops, prefer make use of stream api.

such operation not suited stream api. in functional jargon, you're trying called sliding window of size n. scala has built-in sliding() method, there nothing built-in in java stream api.

you have rely on using stream on indexes of input list make happen.

public static void main(string[] args) {     list<integer> list = arrays.aslist(1, 2, 3, 4, 5, 6, 7);     list<list<integer>> result = ngrams(list, 3);     system.out.println(result); }  private static <t> list<list<t>> ngrams(list<t> list, int n) {     return intstream.range(0, list.size() - n + 1)                     .maptoobj(i -> new arraylist<>(list.sublist(i, + n)))                     .collect(collectors.tolist()); } 

this code makes stream on indexes of input list, maps each of them new list result of getting values of list i i+n (excluded) , collect list.


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -