Java Paste

Java 8 Lambda and Collections Examples


New

Your main class must extend com.ktbyte.submit.Coder

import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class MyProgram extends com.ktbyte.submit.Coder {
    public static void main(String[] args) {
        List<String> names = Arrays.asList(new String[]{"Alice","Bob","Charley","Derp","Ed","F"});
        
        //Sorting with Lambdas:
        Collections.sort(names, Comparator.comparing(String::length));
        System.out.println("Sorted by Length: "+names);
        Collections.sort(names, (a,b)->b.length()-a.length());
        System.out.println("Reverse Sorted by Length: "+names);
        
        //Map - Collect
        System.out.println("Lengths: "+names.stream().map((s)->s.length()).collect(Collectors.toList()));
        
        //java.util.stream.Collectors:
        Map<Integer,String> byLen = names.stream().collect(Collectors.toMap(String::length,Function.<String>identity()));
        System.out.println(byLen.get(5)+" is of length 5");
        
        //Filter
        System.out.println("Length > 3: "+names.stream().filter(s->s.length()>3).collect(Collectors.toList()));
        
        //Average length using Stream.average
        System.out.println("Average Length: "+names.stream().mapToDouble((s)->s.length()).average().getAsDouble());
        
        //Sum length using Stream.sum
        System.out.println("Sum Length: "+names.stream().mapToInt((s)->s.length()).sum());
        
        //Foreach with lambda where argument is specified (String s)
        names.stream().forEach((String s)->{
            System.out.println(s+" is the best!");
        });
        
        //Foreach with inline lambda where argument is inferred (s) [Same as previous Foreach]
        names.stream().forEach((s)->System.out.println(s+" is the best!"));
        
        //Java 7 style lambda: [Same as previous Foreach]
        names.stream().forEach(new Consumer<String>(){
            public void accept(String s) {
                System.out.println(s+" is the best!");
            }
        });
    }
}
Run

Contact