Java scratch scratch

Stream

		List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
		/**
		 *  filter
		 */
		integerList.stream().filter(i -> i % 2 == 0) //Intermediate operation
		.peek(i -> System.out.print("-" + i)) //For Debug
        .forEach(i -> System.out.print("@" + i)); //Termination operation
		// -2@2-4@4

		System.out.println();


		/**
		 * map T -> U
		 */
		integerList.stream().map(i -> i * 2) //Intermediate operation
        .forEach(i -> System.out.print(i + " ")); //Termination operation
		// 2 4 6 8 10

Reconstruct List

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());
}

Sort Map

@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));
	
	//List of Value as Person.Sort by no
	// {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))));
	
	//Key to Person.Sort by id
	// {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;
            });
}

Regular expression pattern matching

	@Test
public void Get the last digit or more() {
		Pattern thisPattern = Pattern.compile("[1-9]{1,}$");
		String str = "13 secrets of the world Season 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 Get full-width number of 1 or more digits at the end() {
		Pattern thisPattern = Pattern.compile("[1-9]{1,}$");
		String str = "13 Secrets of the World Season 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 Get full-width and half-width values of one or more digits at the end() {
		Pattern thisPattern = Pattern.compile("[1-91-9]{1,}$");
		String str = "13 Secrets of the World Season 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 of the World Season 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);
		}
	}

Remove all matches

	@Test
public void Removed key brackets() {
		String str = "text0{A}{B}text1{C}text2{D}text3{E}";
		String actual = recursiveCut(str);
		assertEquals("text0text1text2text3", actual);
	}
	private String recursiveCut(String str) {
		// ?The shortest match when you put
		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(">", "");
	}

	/**
	 *Returns the filename excluding characters that the Windows file system does not allow
	 * @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

	/**
	 *Create a directory when creating a file
	 *
	 * @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


	/**
	 *If a directory is specified, the files under the directory will be deleted.
	 *
	 * @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("File deletion successful");
						break;
					} else {
						System.out.println("File deletion failure");
						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("Directory does not exist");
		}
	}

java6

	/**
	 *If a directory is specified, all files under the directory will be deleted.
	 * @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("File deletion successful");
        				break;
        			} else {
        				System.out.println("File deletion failure");
        				try {
        					Thread.sleep(1000);
        				} catch (InterruptedException e) {
        					e.printStackTrace();
        				}
        			}
        		}
            } else if(file.isDirectory()) {
                File[] files = file.listFiles();

                if(files == null) {
                    System.out.println("File does not exist under");
                }
                //All files in the directory are to be deleted
                for(int i=0; i<files.length; i++) {
                    if(files[i].exists() == false) {
                        continue;
                    //For files, recursively call itself and delete
                    } else if(files[i].isFile()) {
                    	deleteFile(files[i]);
                    }
                }
            }
        } else {
            System.out.println("Directory does not exist");
        }
	}

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<>();
		//When reading from the end
//		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

Java scratch scratch
Java
Java
Java life starting from scratch
Java learning (0)
Studying Java ―― 3
[Java] array
[Java] Annotation
[Java] Module
Java array
Java tips, tips
Java methods
Java method
java (constructor)
Java array
[Java] ArrayDeque
java (override)
java (method)
Java Day 2018
Java string
java (array)
Java static
Java serialization
java beginner 4
Deep Learning Java from scratch 6.4 Regularization
JAVA paid
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Java array
Studying Java ―― 1
[Java] Array
[Java] Polymorphism
Studying Java # 0
Java review
java framework
Java features
[Java] Inheritance
FastScanner Java
Java features
java beginner 3
Java memo
java (encapsulation)
Java inheritance
[Java] Overload
Java basics
Decompile Java
[Java] Annotation
java notes
java beginner
Java (add2)
JAVA (Map)
[java] interface
Java9 collection
Java basics