## Python vs Java Streams and lambda

I ported the first facebook Qualification Round Solution to Java 8.

The main idea is to count the frequency of each letter, then assign the value 26 to the most frequent letter, 25 to the next, etc. If two letters are tied for most frequent, it doesn’t matter which of them gets which value, since the sum will be the same. The python code below explains the solution pretty well.

I haven’t thoroughly checked for bugs but this is almost as beautiful as Python. Java is more verbose though.
I haven’t tested it thoroughly though.

```import java.util.Map;
import java.util.TreeMap;
import java.util.stream.IntStream;

public class WordCount {

public int x = 26;

public static void main(String... argv){

WordCount wc = new WordCount();
wc.count();
}

private void count() {

String s  = "__mainn__".replaceAll("[^a-z\\s]", "");

System.out.println(s);

final Map<Character, Integer> count = s.chars().
map(Character::toLowerCase).
collect(TreeMap::new, (m, c) -> m.merge((char) c, 1, Integer::sum), Map::putAll);

count.entrySet().stream().
sorted((l, r) -> r.getValue().compareTo(l.getValue())).
forEach(e -> count.merge(e.getKey(), x--, Math::multiplyExact));
//Stop when x == 0.Not tested

System.out.println(count.entrySet().stream().mapToDouble(e -> e.getValue()).sum());
//Treating these numbers as double to sum them. Doesn't seem to matter.
}
}
```
```mainn
a-1
i-1
m-1
n-2
{a=25, i=24, m=23, n=52}
124.0
```

## EcmaScript6

I started with this code which motivated me to explore ES6 further.

```        let m = new Map();

m.set("x",3);
m.set("y",5);

for (let [k, value] of m.entries()) {
m.set(k, (m.get(k) * 2))
}

for (let value of m.entries()){
console.log('Value [' + value + ']');

}
```

Earlier I had cooed with pleasure when I coded this.

Now I want to push my luck. So I managed to wangle this code in bits and pieces from some EcmaScript6 aficianodos 🙂

I find it hard to admit that this code is not easy even for someone who claims to have rich experience with Java and software !! Bugs in this code are a different matter altogether.

Moreover since the sorted order changes somehow the result is different than the result of the Java code but I don’t have the motivation to fix this. This is actually an investigation of EcmaScript6 after all.

```        var map = new Map;
Array.from("mainn")
.map(c => c.toLowerCase())
.forEach(c => map.set(c, (map.get(c) | 0) + 1));

let a = [...map.entries()];

var x = 26;
a.sort(([k1, v1], [k2, v2]) => v1 < v2).forEach(([k, v]) =>
{
console.log( 'k [' + k + '] v [' + v * x--+ ']');
});
```
```LOG: 'Value [m,1]'
LOG: 'Value [a,1]'
LOG: 'Value [i,1]'
LOG: 'Value [n,2]'

LOG: 'k [n] v '
LOG: 'k [m] v '
LOG: 'k [a] v '
LOG: 'k [i] v '
```