lambda - Processing a list of maps using Java 8 streams -


how can simplify code single lambda expression? idea there list of maps , create new list of maps, using filter on key. in example, want remap keeps keys "x" , "z".

    map<string, string> m0 = new linkedhashmap<>();     m0.put("x", "123");     m0.put("y", "456");     m0.put("z", "789");      map<string, string> m1 = new linkedhashmap<>();     m1.put("x", "000");     m1.put("y", "111");     m1.put("z", "222");      list<map> l = new arraylist<>(arrays.aslist(m0, m1));     list<map> tx = new arraylist<>();     for(map<string, string> m : l) {         map<string, string> filtered = m.entryset()                 .stream()                 .filter(map -> map.getkey().equals("x") || map.getkey().equals("z"))                 .collect(collectors.tomap(p -> p.getkey(), p -> p.getvalue()));         tx.add(filtered);     }     system.err.println("l: " + l);     system.err.println("tx: " + tx); 

output:

    l: [{x=123, y=456, z=789}, {x=000, y=111, z=222}]     tx: [{x=123, z=789}, {x=000, z=222}] 

of course, can convert entire operation 1 stream operation.

// no need copy list (result of array.aslist) arraylist, way list<map<string, string>> l = arrays.aslist(m0, m1);  list<map<string, string>> tx = l.stream().map(m -> m.entryset().stream()         .filter(map -> map.getkey().equals("x") || map.getkey().equals("z"))         .collect(collectors.tomap(p -> p.getkey(), p -> p.getvalue())))     .collect(collectors.tolist()); 

but note streaming on map , filtering operation linear time complexity, check each key of each map against filter, while have small number of actual keys want retain. here, simpler , more efficient (for larger maps) use

list<map<string, string>> tx = l.stream()     .map(m -> stream.of("x", "y")                     .filter(m::containskey).collect(collectors.tomap(key->key, m::get)))     .collect(collectors.tolist()); 

which perform 4 lookups per map. if bothers you, reduce 2 lookups, however, constant factor irrelevant overall time complexity, constant time, if map has constant time lookup, hashmap. map’s o(log(n)) lookup time complexity, treemap, more efficient linear scan, if maps larger 3 mappings of example code.


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 -