用java8写一个list根据配置文件中写的条件进行skip的共通方法
时间: 2024-05-05 07:15:59 浏览: 119
java向其他机器写文件 共享机器写文件
以下是一个使用Java 8的Stream API实现的具有条件跳过功能的通用方法:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ListSkipper {
public static <T> List<T> skip(List<T> list, String configFile) throws IOException {
Properties props = new Properties();
props.load(Files.newBufferedReader(Paths.get(configFile)));
Map<String, String> conditions = props.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()));
Stream<T> stream = list.stream();
for (Map.Entry<String, String> entry : conditions.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
switch (key) {
case "skipFirst":
stream = stream.skip(Integer.parseInt(value));
break;
case "skipLast":
stream = stream.limit(list.size() - Integer.parseInt(value));
break;
case "skipIfContains":
stream = stream.filter(item -> !item.toString().contains(value));
break;
// Add more cases here for other conditions
default:
throw new IllegalArgumentException("Unknown condition: " + key);
}
}
return stream.collect(Collectors.toList());
}
}
```
使用方法:
```java
List<String> list = Arrays.asList("apple", "banana", "orange", "grape", "kiwi");
// Skip first 2 elements
List<String> result1 = ListSkipper.skip(list, "config1.properties");
System.out.println(result1); // [orange, grape, kiwi]
// Skip last 2 elements
List<String> result2 = ListSkipper.skip(list, "config2.properties");
System.out.println(result2); // [apple, banana]
// Skip elements containing "a"
List<String> result3 = ListSkipper.skip(list, "config3.properties");
System.out.println(result3); // [kiwi]
```
其中,配置文件`config1.properties`的内容为:
```
skipFirst=2
```
配置文件`config2.properties`的内容为:
```
skipLast=2
```
配置文件`config3.properties`的内容为:
```
skipIfContains=a
```
阅读全文