Java Paste

Java 8 Lambda and Collections Examples


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

import java.util.*;
import java.util.function.*;
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: ">s.length()).collect(Collectors.toList()));
        Map<Integer,String> byLen =,Function.<String>identity()));
        System.out.println(byLen.get(5)+" is of length 5");
        System.out.println("Length > 3: ">s.length()>3).collect(Collectors.toList()));
        //Average length using Stream.average
        System.out.println("Average Length: ">s.length()).average().getAsDouble());
        //Sum length using Stream.sum
        System.out.println("Sum Length: ">s.length()).sum());
        //Foreach with lambda where argument is specified (String s) s)->{
            System.out.println(s+" is the best!");
        //Foreach with inline lambda where argument is inferred (s) [Same as previous Foreach]>System.out.println(s+" is the best!"));
        //Java 7 style lambda: [Same as previous Foreach] Consumer<String>(){
            public void accept(String s) {
                System.out.println(s+" is the best!");