java8写一个通过配置文件中的多重条件,对list中满足全部条件的数据进行skip处理的共通方法
时间: 2024-05-08 09:16:28 浏览: 21
以下是一个通过配置文件中的多重条件,对list中满足全部条件的数据进行skip处理的Java 8共通方法的示例代码:
```java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class SkipListByConfig {
public static void main(String[] args) throws IOException {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
list.add("durian");
list.add("elderberry");
list.add("fig");
Properties props = new Properties();
InputStream input = new FileInputStream("config.properties");
props.load(input);
Predicate<String> filter = str -> true;
for (Object key : props.keySet()) {
String[] parts = props.getProperty((String)key).split("=");
String condition = parts[0];
String value = parts[1];
switch (condition) {
case "startsWith":
filter = filter.and(str -> !str.startsWith(value));
break;
case "endsWith":
filter = filter.and(str -> !str.endsWith(value));
break;
case "contains":
filter = filter.and(str -> !str.contains(value));
break;
default:
// ignore
break;
}
}
List<String> result = list.stream()
.filter(filter)
.collect(Collectors.toList());
System.out.println("Original list: " + list);
System.out.println("Filtered list: " + result);
}
}
```
在这个示例中,我们假设我们有一个字符串列表,想要根据配置文件中的多重条件过滤出不符合条件的字符串。配置文件使用键值对的形式,键表示条件类型,值表示条件值,如:`startsWith=a, endsWith=y, contains=rr`。
我们使用Java 8的Stream API来处理列表,并根据配置文件生成一个Predicate来过滤符合条件的元素。最后我们输出过滤前后的列表内容以进行比较。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)