Created
December 10, 2017 12:39
-
-
Save toshimasa-nanaki/eda5c8a2dc6826215771ca88a424c916 to your computer and use it in GitHub Desktop.
Java8 streamサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Scanner; | |
public class AggregateSample { | |
public static final String LINE_SEPARATOR_PATTERN = "\\r\\n|[\\n\\r\\u2028\\u2029\\u0085]"; | |
public static void main(String[] args) { | |
ArrayList<Integer> dataList = new ArrayList<>(); | |
Scanner scan = new Scanner(System.in); | |
scan.useDelimiter("\n"); | |
String line; | |
for (; scan.hasNext();) { | |
line = scan.next(); | |
if(line.matches(LINE_SEPARATOR_PATTERN)) { | |
break; | |
} | |
line = line.replaceAll(LINE_SEPARATOR_PATTERN, ""); | |
try { | |
dataList.add(Integer.valueOf(line)); | |
}catch(NumberFormatException e) { | |
System.err.println("数字を入力してください。"); | |
} | |
} | |
if(dataList.isEmpty()) { | |
System.out.println("数字が入力されていませんでした。"); | |
}else { | |
OutputResult(dataList); | |
} | |
scan.close(); | |
} | |
private static void OutputResult(ArrayList<Integer> dataList) { | |
System.out.println("データ数:" + dataList.size()); | |
System.out.println("合計:" + dataList.stream().mapToInt(x -> x).sum()); | |
System.out.println("平均値:" + dataList.stream().mapToInt(x -> x).average().getAsDouble()); | |
System.out.println("最小値:" + dataList.stream().min((a, b) -> a.compareTo(b)).get()); | |
System.out.println("最大値:" + dataList.stream().max((a, b) -> a.compareTo(b)).get()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment