Java 8を使用して、ファイル内のキー(ハッシュマップから取得)を見つけたいのですが、ファイル内にキーが見つかった場合は、trueと出力されます。以下は私のコードです
public static void main(String[] args) {
String fileName = "C:\\Users\\ABC\\Desktop\\Paper_R2_Final.txt";
Map<String, String> myMap = new HashMap<String,String>();
myMap.put("ecological", "myFirstKey");
myMap.put("Survey", "mySecondKey");
myMap.put("Worth", "myThirdKey");
//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(fileName),StandardCharsets.ISO_8859_1)) {
myMap.forEach((k,v)->System.out.println("key: " + k + ", value: " + v));
//Problem in the below line
System.out.println(stream.anyMatch(line->line.contains((CharSequence) myMap.keySet())));
} catch (IOException e) {
e.printStackTrace();
}
}
これを試して:
public static void main(String[] args) {
String fileName = "C:\\Users\\ABC\\Desktop\\Paper_R2_Final.txt";
Map<String, String> myMap = new HashMap<String,String>();
myMap.put("ecological", "myFirstKey");
myMap.put("Survey", "mySecondKey");
myMap.put("Worth", "myThirdKey");
List<String> myList = new ArrayList<String>(myMap.keySet());
//if the line contains any of the keys
Predicate<String> p = (str) -> myList.stream().anyMatch(key -> str.contains(key));
//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(fileName),StandardCharsets.ISO_8859_1)) {
boolean foundAKey = stream.anyMatch(p);
if(foundAKey) {
//a key is found
}
} catch (IOException e) {
e.printStackTrace();
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加