Java スクラッチ scratch 


## Stream

```java
		List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
		/**
		 *  filter
		 */
		integerList.stream().filter(i -> i % 2 == 0) // 中間操作
		.peek(i -> System.out.print("-" + i)) // Debug用
        .forEach(i -> System.out.print("@" + i)); // 終端操作
		// -2@2-4@4

		System.out.println();


		/**
		 * map T -> U
		 */
		integerList.stream().map(i -> i * 2) // 中間操作
        .forEach(i -> System.out.print(i + " ")); // 終端操作
		// 2 4 6 8 10
```

### Listを再構成する

```java
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());

```

```java
for(Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
}
```
### 2つのMapのvalueを結合してListにする

```java
List<Foo> allUniqueTypeReports = Stream.of(map1.values(), map2.values()).flatMap(m -> m.stream())
			       .collect(Collectors.toList());
```

### Mapをソートする

```java
@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));
	
	// ValueのListをPerson.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をPerson.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;
            });
}
```


## 正規表現 パターンマッチ


```java
	@Test
	public void 末尾の1桁以上の数値を取得() {
		Pattern thisPattern = Pattern.compile("[1-9]{1,}$");
		String str = "世界の13の秘密 シーズン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 末尾の1桁以上の全角数値を取得() {
		Pattern thisPattern = Pattern.compile("[１-９]{1,}$");
		String str = "世界の13の秘密 シーズン２２";
		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 末尾の1桁以上の全角半角数値を取得() {
		Pattern thisPattern = Pattern.compile("[1-9１-９]{1,}$");
		String str = "世界の13の秘密 シーズン２２";
		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の秘密 シーズン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);
		}
	}
```

#### マッチ箇所をすべて取り除く

```java
	@Test
	public void カギカッコ箇所を削除() {
		String str = "text0{A}{B}text1{C}text2{D}text3{E}";
		String actual = recursiveCut(str);
		assertEquals("text0text1text2text3", actual);
	}
	private String recursiveCut(String str) {
		// ?をいれると最短マッチ
		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

```java: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(">", "");
	}

	/**
	 * Windowsファイルシステムで許容しない文字を除いたファイル名を返す
	 * @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

```java
	/**
	 * ファイル作成時にディレクトリも作成する
	 *
	 * @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

```java

	/**
	 * ディレクトリを指定された場合はディレクトリ配下のファイルを削除
	 *
	 * @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("ファイル削除成功");
						break;
					} else {
						System.out.println("ファイル削除失敗");
						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("ディレクトリが存在しません");
		}
	}
```



#### java6

```java
	/**
	 * ディレクトリを指定された場合はディレクトリ配下のファイルをすべて削除する
	 * @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("ファイル削除成功");
        				break;
        			} else {
        				System.out.println("ファイル削除失敗");
        				try {
        					Thread.sleep(1000);
        				} catch (InterruptedException e) {
        					e.printStackTrace();
        				}
        			}
        		}
            } else if(file.isDirectory()) {
                File[] files = file.listFiles();

                if(files == null) {
                    System.out.println("配下にファイルが存在しない");
                }
                // ディレクトリ内の全てのファイルを削除対象とする
                for(int i=0; i<files.length; i++) {
                    if(files[i].exists() == false) {
                        continue;
                    //ファイルの場合は再帰的に自身を呼び出して削除する
                    } else if(files[i].isFile()) {
                    	deleteFile(files[i]);
                    }
                }
            }
        } else {
            System.out.println("ディレクトリが存在しませんン");
        }
	}

```


### write

```java
	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

```java

		Path path = Paths.get(System.getProperty("user.dir"), "data.csv");
		List<String[]> lines = new ArrayList<>();
		// 末尾から読み込む場合
//		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

```java

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