What is Stream?
A sequence of elements supporting sequential and parallel aggregate operations.
How to create?
The java.util.Collection interface has two methods:
- stream()
- parallelStream() - supports parallel computing.
How to use?
The java.util.stream.Stream interface has several methods, here are the most common used.
filter
List<String> strings = Arrays.asList(new String[] { "foo", "bar", "", "code" });
String[] rtn = strings.stream().filter(s -> !s.isEmpty()).toArray(String[]::new);
assertThat(new String[] { "foo", "bar", "code" }, is(equalTo(rtn)));
map
List<String> strings = Arrays.asList(new String[] { "foo", "bar", "code" });
String[] rtn = strings.stream().map(String::toUpperCase).toArray(String[]::new);
assertThat(new String[] { "FOO", "BAR", "CODE" }, is(equalTo(rtn)));
sorted
List<String> strings = Arrays.asList(new String[] { "foo", "bar", "code" });
String[] rtn = strings.stream().sorted().toArray(String[]::new);
assertThat(new String[] { "bar", "code", "foo" }, is(equalTo(rtn)));
forEach
List<String> strings = Arrays.asList(new String[] { "foo", "bar", "code" });
strings.stream().forEach(s -> System.out.println(" >> " + s));
collect
List<String> strings = Arrays.asList(new String[] { "foo", "bar", "code" });
List<String> rtn = strings.stream().collect(toList());
assertThat(strings, is(equalTo(rtn)));
java.util.stream.Collectors
Collectors are used of collecting result from Stream operations, but there are several useful methods in the java.util.stream.Collectors interface. Here some of them.
toList()/toSet()
List<String> strings = Arrays.asList(new String[] { "foo", "bar", "code" });
List<String> rtn = strings.stream().collect(toList());
Set<String> rtn1 = strings.stream().collect(toSet());
groupingBy
Map<String, List<String>> rtn1 = Stream.of("foo", "bar", "code", "foo", "bar").collect(groupingBy(identity()));
System.out.println("groupingBy : " + rtn1);
// {bar=[bar, bar], code=[code], foo=[foo, foo]}
Map<String, Long> rtn2 = Stream.of("foo", "bar", "code", "foo", "bar").collect(groupingBy(identity(), counting()));
System.out.println("groupingBy : " + rtn2);
// {bar=2, code=1, foo=2}
No comments:
Post a Comment