public class StreamTest {
public static void main(String[] args) {
Random random = new Random();
System.out.println("===使用forEach打印5个随机数并排序===");
random.ints().limit(5).sorted().forEach(System.out::println);
System.out.println("========================================");
List<Integer> numbers = Arrays.asList(9,1,2,3,7,8,5);
System.out.println("===使用sorted降序排列====默认升序===");
List<Integer> sortedList = numbers.stream().sorted(Comparator.comparingInt(Integer::intValue).reversed()).collect(Collectors.toList());
System.out.println(sortedList);
System.out.println("========================================");
System.out.println("===使用map将计算元素的结果映射到结果集===");
List<Integer> squaresList = numbers.stream().map(i -> i*(i+1)).collect(Collectors.toList());
System.out.println(squaresList);
System.out.println("========================================");
List<String> strList = Arrays.asList("asd","","dgf","","fghh","asd","dgf");
System.out.println("===使用filter将List中不为空的元素放到另一个List中====");
List<String> filterList = strList.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
System.out.println(filterList);
System.out.println("========================================");
System.out.println("===使用filter将List中不为空的元素放到String中以“;”分割====");
String filterString = strList.stream().filter(s -> !s.isEmpty()).collect(Collectors.joining(";"));
System.out.println(filterString);
System.out.println("========================================");
System.out.println("===使用filter计算List中元素相同的个数====");
Map<String,Integer> map=new HashMap<>();
for (String str:
strList) {
int count = (int) strList.stream().filter(s -> s.equals(str)).count();
if(!map.containsKey(str)&&!"".equals(str)){
map.put(str,count);
}else{
map.put("空字符",count);
}
}
Set<Map.Entry<String,Integer>> entry = map.entrySet();
Iterator<Map.Entry<String,Integer>> iterator = entry.iterator();
while(iterator.hasNext()){
Map.Entry<String,Integer> next = iterator.next();
System.out.println(next);
}
System.out.println("========================================");
}
}
打印结果如下: