Stream
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
/**
* filter
*/
integerList.stream().filter(i -> i % 2 == 0) //Fonctionnement intermédiaire
.peek(i -> System.out.print("-" + i)) //Pour le débogage
.forEach(i -> System.out.print("@" + i)); //Opération de terminaison
// -2@2-4@4
System.out.println();
/**
* map T -> U
*/
integerList.stream().map(i -> i * 2) //Fonctionnement intermédiaire
.forEach(i -> System.out.print(i + " ")); //Opération de terminaison
// 2 4 6 8 10
List<JobTable> jobTable = jobList.stream()
.map(job -> new JobTable(job.getId(), job.getProcessname()))
.collect(Collectors.toList());
Map<Integer, List<Movie>> myListmovieMap = myListMove.stream().collect(
Collectors.groupingBy(Movie::getCategory)
);
Map<Integer, Movie> movieMap = myListMove.stream().collect(
Collectors.toMap(Movie::getTitleNo, e -> e)
);
List<Movie> newMovies = movies.stream()
.filter(e -> !myListmovieMap .containsKey(e.getTitleNo()))
.collect(Collectors.toList());
for(Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
@Data
@AllArgsConstructor
public class Person {
private int categoryId;
private int no;
}
public void sortTest() {
Person p11 = new Person(1,1);
Person p12 = new Person(1,2);
Person p21 = new Person(2,1);
Person p22 = new Person(2,2);
List<Person> persons = Lists.newArrayList(p12, p11, p22, p21);
Map<Integer, List<Person>> personMap = persons.stream()
.collect(Collectors.groupingBy(Person::getCategoryId));
//Liste de valeur en tant que personne.Trier par non
// {1=[Person(categoryId=1, no=1), Person(categoryId=1, no=2)], 2=[Person(categoryId=2, no=1), Person(categoryId=2, no=2)]}
Map<Integer, List<Person>> sortedByValue = persons.stream()
.collect(Collectors.groupingBy(Person::getCategoryId, toSortedList(Comparator.comparing(Person::getNo))));
//Clé de la personne.Trier par identifiant
// {1=[Person(categoryId=1, no=2), Person(categoryId=1, no=1)], 2=[Person(categoryId=2, no=2), Person(categoryId=2, no=1)]}
Map<Integer, List<Person>> sortedByKey = new LinkedHashMap<Integer, List<Person>>();
personMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(e -> sortedByKey.put(e.getKey(), e.getValue()));
}
private <T> Collector<T, ?, List<T>> toSortedList(Comparator<? super T> startDateComparator) {
return Collectors.collectingAndThen(
Collectors.toCollection(ArrayList::new), list -> {
list.sort(startDateComparator);
return list;
});
}
@Test
public void Récupère le dernier chiffre ou plus() {
Pattern thisPattern = Pattern.compile("[1-9]{1,}$");
String str = "13 Secrets du Monde Saison 12";
Matcher m = thisPattern.matcher(str);
if (m.find()) {
int start = m.start();
int end = m.end();
int resutl = Integer.parseInt(str.substring(start, end));
System.out.println(resutl); // 12
}
}
@Test
public void Récupère la valeur numérique pleine largeur d'un ou plusieurs chiffres à la fin() {
Pattern thisPattern = Pattern.compile("[1-9]{1,}$");
String str = "13 Secrets du Monde Saison 22";
Matcher m = thisPattern.matcher(str);
if (m.find()) {
int start = m.start();
int end = m.end();
int resutl = Integer.parseInt(str.substring(start, end));
System.out.println(resutl); // 22
}
}
@Test
public void Obtenez des nombres pleine largeur et demi-largeur avec un ou plusieurs chiffres à la fin() {
Pattern thisPattern = Pattern.compile("[1-91-9]{1,}$");
String str = "13 Secrets du Monde Saison 22";
Matcher m = thisPattern.matcher(str);
if (m.find()) {
int start = m.start();
int end = m.end();
int resutl = Integer.parseInt(str.substring(start, end));
System.out.println(resutl);
}
String str2 = "13 Secrets du Monde Saison 22";
Matcher m2 = thisPattern.matcher(str2);
if (m2.find()) {
int start = m2.start();
int end = m2.end();
int resutl = Integer.parseInt(str2.substring(start, end));
System.out.println(resutl);
}
}
@Test
public void Suppression des crochets de clé() {
String str = "text0{A}{B}text1{C}text2{D}text3{E}";
String actual = recursiveCut(str);
assertEquals("text0text1text2text3", actual);
}
private String recursiveCut(String str) {
// ?Le match le plus court quand vous mettez
Pattern thisPattern = Pattern.compile("\\{.+?\\}");
Matcher m = thisPattern.matcher(str);
String result = null;
if (m.find()) {
int start = m.start();
int end = m.end();
result = str.substring(0, start);
result += str.substring(end, str.length());
result = recursiveCut(result);
} else {
return str;
}
return result;
}
File validate
FileHelper.java
public class FileHelper {
private static Map<String, String> invalidFileChar = new HashMap<>();
@Test
public void getValidFilenameTest() {
List<String> invalidFileNames = new ArrayList<>();
invalidFileNames.add("file.txt|small");
invalidFileNames.add("file.txt/small");
invalidFileNames.add("file.txt?small");
invalidFileNames.add("file.txt\\small");
invalidFileNames.add("file.txt:small");
invalidFileNames.add("file.txt\"small");
invalidFileNames.add("file.txt<small");
invalidFileNames.add("file.txt>small");
for (String invalidFileName : invalidFileNames) {
String validFileName = FileHelper.getValidFilename(invalidFileName);
assertEquals("file.txt", validFileName);
}
}
public FileHelper() {
this.invalidFileChar.put("|", "");
this.invalidFileChar.put("/", "");
this.invalidFileChar.put("?", "");
this.invalidFileChar.put("\\", "");
this.invalidFileChar.put(":", "");
this.invalidFileChar.put("*", "");
this.invalidFileChar.put("\"", "");
this.invalidFileChar.put("<", "");
this.invalidFileChar.put(">", "");
}
/**
*Renvoie le nom du fichier à l'exclusion des caractères que le système de fichiers Windows n'autorise pas
* @param fileName
* @return
*/
public static String getValidFilename(String fileName) {
String validFileName = fileName;
for (Map.Entry<String, String> entry : invalidFileChar.entrySet()) {
String invalidChar = entry.getKey();
if (fileName.contains(invalidChar)) {
switch (invalidChar) {
// Regular-Expressions special character
case "\\":
case "*":
case "+":
case ".":
case "?":
case "{":
case "}":
case "(":
case ")":
case "[":
case "]":
case "^":
case "$":
case "–":
case "|":
validFileName = fileName.split(Pattern.quote(invalidChar))[0];
break;
default:
validFileName = fileName.split(invalidChar)[0];
}
}
}
return validFileName;
}
}
create
/**
*Créer un répertoire lors de la création d'un fichier
*
* @param file
*/
private static void createFile(File file) {
Path path = file.toPath();
if (Files.exists(path)) {
return;
}
try {
Files.createDirectories(path.getParent());
Files.createFile(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
delete
java7
/**
*Si un répertoire est spécifié, les fichiers sous le répertoire seront supprimés.
*
* @param file
*/
private static void deleteFile(File file) {
Path path = file.toPath();
if (Files.exists(path)) {
if (file.isFile()) {
for (int i = 0; i < 100; i++) {
if (file.delete()) {
System.out.println("Suppression du fichier réussie");
break;
} else {
System.out.println("Échec de la suppression du fichier");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} else if (Files.isDirectory(path)) {
try (Stream<Path> walk = Files.walk(path, FileVisitOption.FOLLOW_LINKS)) {
walk.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
path.toFile().delete();
} catch (IOException ie) {
System.out.println(ie);
}
}
} else {
System.out.println("Le répertoire n’existe pas");
}
}
java6
/**
*Si un répertoire est spécifié, tous les fichiers du répertoire seront supprimés.
* @param file
*/
private void deleteFile(File file) {
if(file.exists()) {
if(file.isFile()) {
for (int i = 0; i < 100; i++) {
if (file.delete()) {
System.out.println("Suppression du fichier réussie");
break;
} else {
System.out.println("Échec de la suppression du fichier");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} else if(file.isDirectory()) {
File[] files = file.listFiles();
if(files == null) {
System.out.println("Le fichier n'existe pas sous");
}
//Tous les fichiers du répertoire doivent être supprimés
for(int i=0; i<files.length; i++) {
if(files[i].exists() == false) {
continue;
//Dans le cas d'un fichier, il s'appelle récursivement et le supprime.
} else if(files[i].isFile()) {
deleteFile(files[i]);
}
}
}
} else {
System.out.println("Le répertoire n'existe pas");
}
}
write
public static void main(String[] args) throws IOException {
String path = Paths.get(System.getProperty("user.dir"), "sample", "test.txt").toString();
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(path);
PrintWriter pw = new PrintWriter(new BufferedWriter(writer));
pw.println("apple");
pw.println("orange");
pw.println("melon");
pw.close();
// file.delete();
}
read
Path path = Paths.get(System.getProperty("user.dir"), "data.csv");
List<String[]> lines = new ArrayList<>();
//Lors de la lecture de la fin
// try (ReversedLinesFileReader reader = new ReversedLinesFileReader(path.toFile())) {
try (BufferedReader reader = Files.newBufferedReader(path)) {
String str;
while ((str = reader.readLine()) != null) {
lines.add(str.split(","));
}
} catch (IOException e) {
e.printStackTrace();
}
for (String[] cols : lines) {
for (String col : cols) {
System.out.print(col + " ");
}
}
Time
private LocalDateTime now;
private Timestamp now_timestamp;
private LocalDateTime before10min;
private Timestamp before10min_timestamp;
private LocalDateTime after10min;
private Timestamp after10min_timestamp;
@Before
public void setUp() {
now = LocalDateTime.now();
now_timestamp = Timestamp.valueOf(now);
before10min = now.minusMinutes(10);
before10min_timestamp = Timestamp.valueOf(before10min);
after10min = now.plusMinutes(10);
after10min_timestamp = Timestamp.valueOf(after10min);
}
@Test
public void afterMathodTest() {
assertTrue(now.isAfter(before10min));
assertTrue(now_timestamp.after(before10min_timestamp));
}
@Test
public void beforeMathodTest() {
assertTrue(before10min.isBefore(now));
assertTrue(before10min_timestamp.before(now_timestamp));
}
@Test
public void beforeAndAfterMathodTest() {
assertTrue(before10min.isBefore(now) && after10min.isAfter(now));
assertTrue(before10min_timestamp.before(now_timestamp) && after10min_timestamp.after(now_timestamp));
}
Recommended Posts