Java 8 Stream示例

  本文提供java 8的concat,count,sorted和distinct等流API方法的示例。

Stream.concat

concat()是流API中的静态方法。它汇总两个流对象并返回结果流对象。在我们的示例中,我们有两个列表,它们被转换为流然后连接。 

public class ConcatDemo {
public static void main(String[] args) {
List<String> list1 = Arrays.asList("A1","A2","A3");
List<String> list2 = Arrays.asList("B1","B2","B3");
Stream<String> resStream = Stream.concat(list1.stream(), list2.stream());
resStream.forEach(s->System.out.println(s));
}
}

输出:

A1  A2  A3  B1  B2  B3

Stream.count

count() 只计算流对象中的元素。它返回long值。在我们的示例中,我们有一个列表,我们将其转换为流,然后对其应用count()方法。 
public class CountDemo {
public static void main(String[] args) {
List<String> list = Arrays.asList("AA","AB","CC");
Predicate<String> predicate = s-> s.startsWith("A");
long l= list.stream().filter(predicate).count();
System.out.println("Number of Matching Element:"+l);
}
}

输出:

Number of Matching Element:2 

 

Stream.sorted

根据自然顺序对流的元素进行排序。我们还可以传递比较器对象以获得自定义排序。 
public class SortedDemo {
public static void main(String[] args) {
List<String> list = Arrays.asList("DC","CD","AD");
list.stream().sorted().forEach(s->System.out.println(s));
}
}

输出:

AD  CD  DC 

 

Stream.distinct

distinct()方法返回不同元素的流。不同的元素判断由Object类的equal 方法决定。 
public class DistinctDemo {
public static void main(String[] args) {
List<String> list = Arrays.asList("AA","AA","BB");
long l = list.stream().distinct().count();
System.out.println("Number of distinct element:"+l);
}
}

 

Stream.mapToInt

将流中每个元素的返回结果变为int类型,然后使用sum累计:

List<A> as = new ArrayList<A>();
as.add(new A(1));
as.add(new A(2));
as.add(new A(3));
System.out.println("=" + as.stream().mapToInt(a -> a.getCount()).sum());
public class A {

private final int count;

public A(int count) {
this.count = count;
}

public int getCount() {
return count;
}
}

结果是:6

Java基础

 

猜你喜欢