Skip to main content

Java Lambda Snippets

Java Lambda Snippets

/*
* This page is a running list of java lambda code snippets. 
* It lacks details on what each statement actually does. 
* If you are not comfortable with lambda then please
* refer to a good reference book on lambdas.
*/
//map and collect list of string to a comma seperated string
 list.stream()
  .map(i -> i % 2 == 0 ? "e" + i : "o" + i)
  .collect(joining(","));
 
//filter and collect into list
 list.stream()
  .filter(s -> s.startsWith("a"))
  .filter(s -> s.length() == 3)
  .collect(Collectors.toList());
 
//convert comma separated string pair to map
Map returnData = new HashMap<>();
rows.stream().map((row) -> row.split(",")).forEach((rowData) -> {
            returnData.put(rowData[keyColumn], rowData[valueColumn]);
        });
//-------------------------------------------
//Use lambda to find specific aggregate from list of objects
        Trader raoul = new Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");
        List transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );
        // Query 1: Find all transactions from year 2011 and sort them by value (small to high).
        List tr2011 = transactions.stream()
                .filter(transaction -> transaction.getYear() == 2011)
                .sorted(comparing(Transaction::getValue))
                .collect(toList());
        System.out.println(tr2011);
        // Query 2: What are all the unique cities where the traders work?
        List cities
                = transactions.stream()
                .map(transaction -> transaction.getTrader().getCity())
                .distinct()
                .collect(toList());
        System.out.println(cities);
        // Query 3: Find all traders from Cambridge and sort them by name.
        List traders
                = transactions.stream()
                .map(Transaction::getTrader)
                .filter(trader -> trader.getCity().equals("Cambridge"))
                .distinct()
                .sorted(comparing(Trader::getName))
                .collect(toList());
        System.out.println(traders);
        // Query 4: Return a string of all traders̢۪ names sorted alphabetically.
        String traderStr
                = transactions.stream()
                .map(transaction -> transaction.getTrader().getName())
                .distinct()
                .sorted()
                .reduce("", (n1, n2) -> n1 + n2);
        System.out.println(traderStr);
        // Query 5: Are there any trader based in Milan?
        boolean milanBased
                = transactions.stream()
                .anyMatch(transaction -> transaction.getTrader()
                        .getCity()
                        .equals("Milan")
                );
        System.out.println(milanBased);
        // Query 6: Update all transactions so that the traders from Milan are set to Cambridge.
        transactions.stream()
                .map(Transaction::getTrader)
                .filter(trader -> trader.getCity().equals("Milan"))
                .forEach(trader -> trader.setCity("Cambridge"));
        System.out.println(transactions);
        // Query 7: What's the highest value in all the transactions?
        int highestValue
                = transactions.stream()
                .map(Transaction::getValue)
                .reduce(0, Integer::max);
        System.out.println(highestValue);
//-------------------------------------------------------
//More example of comparator in lambda
List babies = BabyNamesParserUtil.getBabyNames(2000);
        List filtered = babies.stream().filter(
                p -> p.getGender().equalsIgnoreCase("F")).sorted(Comparator.comparing(Baby::getOccurance).reversed())
                .limit(10).collect(Collectors.toList());
        System.out.println("Top 10 female baby names >>>>>>");
        filtered.forEach(b -> System.out.println(b.toString()));
        List mfiltered = babies.stream().filter(
                p -> p.getGender().equalsIgnoreCase("M")).sorted(Comparator.comparing(Baby::getOccurance).reversed())
                .limit(10).collect(Collectors.toList());
        System.out.println("\n\nTop 10 male baby names >>>>>>");
        mfiltered.forEach(b -> System.out.println(b.toString()));
//---------------------------------------
// Regex that matches one or more consecutive whitespace characters
        Pattern pattern = Pattern.compile("\\s+");

        // count occurrences of each word in a Stream sorted by word
        Map wordCounts
                = Files.lines(Paths.get("C:\\java8\\LambdaPresentation\\data\\LambdaPresentation\\data\\MobyDick.txt")) //Util function returns stream of all the lines in a file
                .map(line -> line.replaceAll("(?!')\\p{P}", ""))
                .flatMap(line -> pattern.splitAsStream(line)) //Pattern got new method splitAsStream to split as CharSequence
                .collect(Collectors.groupingBy(String::toLowerCase,
                                TreeMap::new, Collectors.counting()));

        // display the words grouped by starting letter
        wordCounts.entrySet()
                .stream().filter(entry -> StringUtils.isNotBlank(entry.getKey()) && Character.isLetter(entry.getKey().trim().charAt(0)))
                .collect(Collectors.groupingBy(entry -> entry.getKey().trim().charAt(0),
                                TreeMap::new, Collectors.toList()
                        ))
                .forEach((letter, wordList)
                        -> {
                    System.out.printf("%n%C%n", letter);
                    wordList.stream().forEach(word -> System.out.printf(
                                    "%13s: %d%n", word.getKey(), word.getValue()));
                });
//----------------------------------------
//Stream. Iterate
Stream.iterate(5.0, p -> p * 2)
                .peek(e -> System.out.println("Fetching " + e)) // peek is a good tool for debugging
                .limit(5).toArray();
//parallel stream
Map airports = CSVUtil.readAsMap("C:\\java8\\LambdaPresentation\\data\\airports.csv", 0, 1);
            airports.keySet().parallelStream().forEach(p -> { //now try with parallelStream
                System.out.println("Airport Code : " + p);
                System.out.println("Airport Name : " + airports.get(p));
                System.out.println("Is Delay : " + FAAUtil.contactFAA(p).isIsDelay());
            });
List coldAirports
                    = airports.stream().filter(a -> a.getTemperatue() < 40) //try parallel
                    .sorted(comparing(Airport::getTemperatue).reversed())
                    .map(a -> a.getCode())
                    .collect(Collectors.toList());
//IntStream
List list = IntStream.of(100,300,500,600,700,800).boxed().collect(Collectors.toList());
        list.forEach(p->System.out.println(p));
//Secure random
SecureRandom random = new SecureRandom();

        // roll a die 1,000,000 times and summarize the results
        System.out.printf("%-6s%s%n", "Face", "Frequency");
        random.ints(6_000_000, 1, 7) //created infinite stream
                .boxed() //important otherwise collect wont work on these streams
                .collect(Collectors.groupingBy(Function.identity(),
                                Collectors.counting()))
                .forEach((face, frequency)
                        -> System.out.printf("%-6d%d%n", face, frequency));

//Java 9 features for Optional and Stream
List integerList = List.of(1,2,45,55,78,98);
  System.out.println("Take while output");
  integerList.stream().takeWhile(i -> i< 55).forEach(System.out::println);
  
  System.out.println("Drop while output");
  integerList.stream().dropWhile(i -> i< 55).forEach(System.out::println);
  
  System.out.println("Mimic for loop");
  IntStream.iterate(0, i -> i+1).limit(4).forEach(System.out::println);
  
  //get orElse methods in stream can be replaced with Optional ifPresentElse
  Optional mayBeInteger = integerList.stream().filter(s -> s > 100).findAny();
  mayBeInteger.ifPresentOrElse(System.out::println, () -> System.out.println("Empty Result!"));
  
  //Map method in Optional is also smarter now
  Optional mayBeAnotherInteger = integerList.stream().filter(s -> s > 100).findAny();
  Optional definitelyInteger = mayBeAnotherInteger.or(()-> Optional.of(-999));
  System.out.println(definitelyInteger.get());
  
  //Optional can also be converted to stream now, it will always have at most one value.
  Stream optionalStream = integerList.stream().filter(s -> s < 100).findFirst().stream();

Popular posts from this blog

Code refactoring is not an end of year task

Refactoring is one of the best practices of  Extreme programming . Even the most stable project requires occasional modification. The idea is to clean up duplication and smelly code. The principle of software entropy suggests that program starts off in a well-designed state, but as new bits of functionality are tacked on, programs gradually lose their structure. We write a small program that does a specific job well. Later we add new functionality on top of existing program, often in a way that the existing program was not intended to support. In such cases, we can either do a complete redesign or patch some work around. Redesign and rewriting existing code results in extra work, which in most cases we can’t afford. Also, we may miss existing functionality or introduce new bugs. The principle usually followed is: “If it ain’t broke, don’t fix it!”. However, if a code is made complex due to poor design choices and unnecessary constructs then it starts emanating code smell. ...

The Future of Java

There is no doubt that Java has held the title of the most popular programming language for many years ( credit stackify , codingdojo  and  vintaytime ). Even if you agree with the various stats, we can easily come a consensus that Java is one of the top ten most widely used  language in the enterprise world and most sought-after job skill  for a software developer. I am not here to argue if Java really deserves its current spot but to predict (if I may), how it would evolve in coming years. Ever since Oracle took over  the command and control of JDK development since 2009, there has been skepticism over the future of Java. Luckily we had several enhancements to Java in JDK 7 and 8, which restored the confidence we all have put in Java over many years. Java as a language had its flaws and drawbacks, which other languages (old and new) tried to fill in. The real star was always JVM ( the runtime environment on which Java runs and makes it platform ind...

Welcome to My Developer Connect.

Welcome to  The goal of this blog site is to provide programming best practices and tips to developers. Whether you are a new software developer or an experienced one, I hope you will find something useful on this site. No matter where your passion for programming leads you, I wish you all the best on this incredible journey. Govind Mekala