1、打印集合中的数据
java
复制代码
List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu");
//打印集合内的数据
for(String s : list){
System.out.println(s);
}
list.forEach(System.out::println);
2、列表排序
java
复制代码
List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu");
list.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
list.sort((s1, s2) -> s1.compareTo(s2));
3、过滤列表
java
复制代码
List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu");
List<String> list2 = list.stream().filter(s ->
s.startsWith("z")).collect(Collectors.toList());
4、映射:获取列表中的每个元素的长度
java
复制代码
List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu");
List<Integer>list3 = new ArrayList<>();
for(String s : list){
list3.add(s.length());
}
List<Integer>list4 = list.stream().map(s -> s.length()).collect(Collectors.toList());
5、对列表中的数据进行求和操作
java
复制代码
List<Integer> list5 = Arrays.asList(1,2,3,4,5);
Integer sum1 = 0;
for(Integer i : list5){
sum1 += i;
}
int sum2 = list5.stream().reduce(0, (a, b) -> a + b);
6、分组操作
java
复制代码
List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu");
Map<Integer, List<String>> group = new HashMap<>();
for(String s : list){
if(!group.containsKey(s.length())){
group.put(s.length(), new ArrayList<>());
}
group.get(s.length()).add(s);
}
Map<Integer, List<String>>group2 = list.stream().collect(Collectors.groupingBy(String::length));
Map<Integer, List<String>>group3 = list.stream().collect(Collectors.groupingBy(s -> s.length()));
7、实现接口
java
复制代码
MyInterFace myInterFace = new MyInterFace() {
@Override
public void doSomeThing(String s) {
System.out.println(s);
}
};
MyInterFace myInterFace1 = s -> System.out.println(s);
public interface MyInterFace{
void doSomeThing(String s);
}
8、创建线程
java
复制代码
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello world");
}
});
thread.start();
Thread thread1 = new Thread(() -> System.out.println("hello word"));
thread1.start();
9、进行判空操作
java
复制代码
String str = "hello word";
if(str != null) str.toUpperCase();
Optional.ofNullable(str).map(String::toUpperCase).ifPresent(System.out::println);
10、流水线操作
java
复制代码
List<String> list6 = new ArrayList<>();
for(String s : list){
if(s.startsWith("a")){
list6.add(s.toUpperCase());
}
}
Collections.sort(list6);
List<String> list7 = list.stream().filter(s -> s.startsWith("a")).map(String::toUpperCase).sorted().collect(Collectors.toList());