Java 8 straming API examples

For this list:

List<String> users = Arrays.asList("Alice", "Bob", "Bob", "Josh", "Zair", "Mat");

AveragingDouble

double avgLength = users.stream().collect(Collectors.averagingDouble(String::length));
System.out.println("Average length: "+avgLength);

Will produce:
Average length: 3.6666666666666665

Joining

String joined = users.stream().collect(Collectors.joining("|"));
System.out.println(joined);

Will produce:
Alice|Bob|Bob|Josh|Zair|Mat

Other Streaming API Examples
Filter
Here is an example of filtering:

  List<String> users = Arrays.asList("Alice", "Bob", "Josh", "Zair", "Mat");
    users
    .stream()
    .filter(x -> x.length() == 4)
    .forEach(x -> System.out.println(x));
  }

Map

List<String> uppercased =  users.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(uppercased);
//OR
uppercased =  users.stream().map(x -> x.toUpperCase()).collect(Collectors.toList());
System.out.println(uppercased);

MapToInt

   List<String> users = Arrays.asList("Alice", "Bob", "Josh", "Zair", "Mat");
    users
    .stream()
    .mapToInt(x -> x.length())
    .forEach(x -> System.out.println(x));
//OR
    users
    .stream()
    .mapToInt(String::length)
    .forEach(System.out::println);

Count

System.out.println(users.stream().count());

Distinct

List<String> distinctUsers = users.stream().distinct().collect(Collectors.toList());
usersunique.stream().forEach(System.out::println);

Limit

List<String> limited = users.stream().limit(4).collect(Collectors.toList());
    	System.out.println(limited);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s