Java Arrays convert array to Stream

Description

Java Arrays convert array to Stream

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    Integer[] values = { 2, 9, 5, 0, 3, 7, 1, 4, 8, 6 };

    // display original values
    System.out.printf("Original values: %s%n", Arrays.asList(values));

    Stream<Integer> s = Arrays.stream(values);
    /*from www  .j  ava  2 s . c  o  m*/
    List<Integer> list = s.sorted().collect(Collectors.toList());
    
    System.out.printf("Sorted values: %s%n", list);
  }
}

Process String array

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] args) {
    String[] strings = { "CSS", "Java", "HTML", "Javascript", "SQL", "C++", "C" };
    // display original strings
    System.out.printf("Original strings: %s%n", Arrays.asList(strings));

    // strings in uppercase
    System.out.printf("strings in uppercase: %s%n",
        Arrays.stream(strings).map(String::toUpperCase).collect(Collectors.toList()));

    // strings less than "n" (case insensitive) sorted ascending
    System.out.printf("strings greater than m sorted ascending: %s%n",
        Arrays.stream(strings).filter(s -> s.compareToIgnoreCase("n") < 0).sorted(String.CASE_INSENSITIVE_ORDER)
            .collect(Collectors.toList()));

    // strings less than "n" (case insensitive) sorted descending
    System.out.printf("strings greater than m sorted descending: %s%n",
        Arrays.stream(strings).filter(s -> s.compareToIgnoreCase("n") < 0)
            .sorted(String.CASE_INSENSITIVE_ORDER.reversed()).collect(Collectors.toList()));
  }//from w  w w .  jav a  2 s .  co m
}



PreviousNext

Related