Monday, November 3, 2014

Java important pro



Filter and then find the first or return the default value

import java.util.Arrays;
import java.util.List;
           public class Main 
           {
  public static void main(String[] args) 
  {
     List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
     int i = numbers.stream().filter(n -> n % 2 == 0).findFirst().orElse(-1);
               System.out.println(i);
   }
 
}

Filter even number                       

import java.util.Arrays;
import java.util.List;
           public class Main 
{
 public static void main(String[] args) 
{
     List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
     numbers.stream().filter(n -> n % 2 == 0).forEach(System.out::println);
   }
          }

Filter number list and get even numbers

import java.util.Arrays;
import java.util.List;
public class Main 
{
           public static void main(String[] args) 
           {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    numbers.stream()
           .filter(value -> value % 2 == 0)
           .forEach(System.out::println);
  }
}

Filter twice

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class Main 
{
            public static void main(String[] args)  
           {
    List liste = Arrays.asList("Xml", "Html", "Css", null);
               liste.parallelStream()
            .filter(e -> (!Objects.equals(e, null))) 
            .filter(e -> (e.length() > 3)) 
            .forEach(e -> 
            {  
                System.out.println("Bigger length than 3 in List: " + e);
            });
                }
}

Find first matched item

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class Main 
{
           public static void main(String[] args) 
           {
    List names = Arrays.asList("XML", "HTML", "Java", "Javascript", "CSS", "Static");
           Optional firstS = names.stream().filter(name ->  name.startsWith("S")).findFirst();
    System.out.println(firstS.orElse("None found"));
  }
}

Output default if not found

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class Main 
{
           public static void main(String[] args) 
           {
    List names = Arrays.asList("XML", "HTML", "Java", "Javascript", "CSS", "Static");
 
    Optional firstS = names.stream().filter(name -> name.startsWith("S")).findFirst();
    System.out.println(firstS.orElse("None found"));
  }
}

No comments:

Post a Comment