java 8 - How to express the code with lambda? -


i want convert list map

public map<integer, a> tomap(list<a> list) {     map<integer, a> map = new hashmap<>();     int sum = 0;     (int = 0; < list.size(); i++) {         if (list.get(i).getkey() != 0) {             sum += math.abs(list.get(i).getkey());             map.put(sum, list.get(i));         }     }     return map; } 

how express lambda?

maybe using foreach more effectively. not have convert stream when violate kiss , for, foreach,while loop not dead. giving stream code later bit more big.

foreach

public map<integer, a> tomap(list<a> list) {     map<integer, a> map = new hashmap<>();     int prevkey = 0;     (a item : list) {         int key = item.getkey();          if (key != 0) {             map.put(prevkey += math.abs(key), item);         }     }     return map; } 

combine foreach & stream

or maybe need combine foreach & stream describe doing 2 things filtering & mapping.

public map<integer, a> tomap(list<a> list) {     map<integer, a> map = new hashmap<>();     int prevkey = 0;     (a item : each(list.stream().filter(it -> it.getkey() != 0))) {         map.put(prevkey += math.abs(item.getkey()), item);     }     return map; }  private static <t> iterable<? extends t> each(stream<t> stream) {     return stream::iterator; } 

stream using stream.collect(collector)

import java.util.list; import java.util.map; import java.util.concurrent.atomic.atomicinteger; import java.util.function.function; import java.util.stream.collectors; import static java.util.function.function.identity;  public map<integer, a> tomap(list<a> list) {     atomicinteger prevkey = new atomicinteger(0);     return list.stream().filter(it -> it.getkey() != 0)                .collect(collectors.tomap(curry(prevkey::addandget, a::getkey)                                               ,identity())); }  // e.g: atomicinteger.addandget(a.getkey()) <t, u, r> function<t, r> curry(function<u, r> target, function<t, u> mapper) {     return (it) -> target.apply(mapper.apply(it)); } 

stream using stream.collect(supplier, biconsumer, biconsumer)

import java.util.abstractmap.simpleentry; import java.util.map.entry; import java.util.stack; import java.util.stream.collectors; import java.util.map;  public map<integer, a> tomap(list<a> list) {     return list.stream().filter(it -> it.getkey() != 0).             collect(stack::new, this::calculatekey, stack::addall).stream().             collect(collectors.tomap(entry::getkey, entry::getvalue)); }  private void calculatekey(stack<entry<integer, a>> stack, a) {     integer prevkey = stack.isempty() ? 0 : stack.peek().getkey();      integer key = prevkey + a.getkey();      stack.push(new simpleentry<>(key, a)); } 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -