Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
using System;
using System.Collections.Generic;
using System.Linq;
public static class Program
public static void Main()
var names = new List<string> { "Alice", "Bob", "Charley", "Derp", "Ed", "F" };
names.Sort((a, b) => a.Length - b.Length);
Console.WriteLine("Sorted by Length: " + string.Join(", ", names));
names.Sort((a, b) => b.Length - a.Length);
Console.WriteLine("Reverse sorted by Length: " + string.Join(", ", names));
names.Sort((a, b) => a.Length - b.Length);
Console.WriteLine("Reverse (alt) sorted by Length: " + string.Join(", ", names));
var map = names.Select(e => new { K = e.Length, V = e }).ToDictionary(e => e.K, e => e.V);
Console.WriteLine("Map by length: ");
Console.WriteLine(string.Join(Environment.NewLine, map.Select(e => string.Format("{0}: {1}", e.Key, e.Value))));
Console.WriteLine("Of length 5");
Console.WriteLine(string.Join(Environment.NewLine, map[5]));
Console.WriteLine("Length > 3");
Console.WriteLine(string.Join(Environment.NewLine, names.Where(e => e.Length > 3)));
Console.WriteLine("Average length: " + names.Select(e => e.Length).Average());
Console.WriteLine("Sum length: " + names.Sum(e => e.Length));
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!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.