質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Q&A

4回答

390閲覧

Java:コードをスッキリさせたい

退会済みユーザー

退会済みユーザー

総合スコア0

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

0グッド

0クリップ

投稿2019/09/27 01:19

Javaのコードを整理して書きたいと考えています。
以下のようなコードを書き、動作できることは確認済みです。
ですが変数やif文が多すぎるので、もっとスッキリ書きたいのですが、
直す方法があれば教えていただけますか。

<やりたいこと>
DBからリスト形式でデータを取得し、該当するデータの数をカウントして
回数をテーブル(html)に表示させたい。

<データの例>
triangle white
circle red
circle blue
rhombus yellow
ellipse white
circle black
・ ・
・ ・
・ ・
・ ・

<テーブル>


      • | circle | triangle | square | ellipse | rhombus | total

red | cnt_f1c1 | cnt_f2c1 | cnt_f3c1 | cnt_f4c1 | cnt_f5c1 | cnt_c1


blue | cnt_f1c2 | cnt_f2c2 | cnt_f3c2 | cnt_f4c2 | cnt_f5c2 | cnt_c2


yellow | cnt_f1c3 | cnt_f2c3 | cnt_f3c3 | cnt_f4c3 | cnt_f5c3 | cnt_c3


black | cnt_f1c4 | cnt_f2c4 | cnt_f3c4 | cnt_f4c4 | cnt_f5c4 | cnt_c4


white | cnt_f1c5 | cnt_f2c5 | cnt_f3c5 | cnt_f4c5 | cnt_f5c5 | cnt_c5


total | cnt_f1 | cnt_f2 | cnt_f3 | cnt_f4 | cnt_f5 | record


<ソースコード>
private String getDB(Model model){

List<Table1Entity> table1DataList = table1Repository.findAll(); int record = table1DataList.size(); int cnt_f1 = 0, cnt_f2 = 0, cnt_f3 = 0, cnt_f4 = 0, cnt_f5 = 0; int cnt_c1 = 0, cnt_c2 = 0, cnt_c3 = 0, cnt_c4 = 0, cnt_c5 = 0; int cnt_f1c1 = 0, cnt_f1c2 = 0, cnt_f1c3 = 0, f1c4 = 0, f1c5 = 0; int cnt_f2c1 = 0, cnt_f2c2 = 0, cnt_f2c3 = 0, f2c4 = 0, f2c5 = 0; int cnt_f3c1 = 0, cnt_f3c2 = 0, cnt_f3c3 = 0, f3c4 = 0, f3c5 = 0; int cnt_f4c1 = 0, cnt_f4c2 = 0, cnt_f4c3 = 0, f4c4 = 0, f4c5 = 0; int cnt_f5c1 = 0, cnt_f5c2 = 0, cnt_f5c3 = 0, f5c4 = 0, f5c5 = 0; for (int i = 0; i < record; i++) { String form = table1DataList.get(i).getForm(); String color = table1DataList.get(i).getColor(); if("circle".equals(form)) { cnt_f1 += 1; if("red".equals(color)) { cnt_f1c1 += 1; } else if ("blue".equals(color)) { cnt_f1c2 += 1; } else if ("yellow".equals(color)) { cnt_f1c3 += 1; } else if ("black".equals(color)) { cnt_f1c4 += 1; } else if ("white".equals(color)) { cnt_f1c5 += 1; } } else if ("triangle".equals(form)) { cnt_f2 += 1; if("red".equals(color)) { cnt_f2c1 += 1; } else if ("blue".equals(color)) { cnt_f2c2 += 1; } else if ("yellow".equals(color)) { cnt_f2c3 += 1; } else if ("black".equals(color)) { cnt_f2c4 += 1; } else if ("white".equals(color)) { cnt_f2c5 += 1; } } else if ("square".equals(form)) { cnt_f3 += 1; if("red".equals(color)) { cnt_f3c1 += 1; } else if ("blue".equals(color)) { cnt_f3c2 += 1; } else if ("yellow".equals(color)) { cnt_f3c3 += 1; } else if ("black".equals(color)) { cnt_f3c4 += 1; } else if ("white".equals(color)) { cnt_f3c5 += 1; } } else if ("ellipse".equals(form)) { cnt_f4 += 1; if("red".equals(color)) { cnt_f4c1 += 1; } else if ("blue".equals(color)) { cnt_f4c2 += 1; } else if ("yellow".equals(color)) { cnt_f4c3 += 1; } else if ("black".equals(color)) { cnt_f4c4 += 1; } else if ("white".equals(color)) { cnt_f4c5 += 1; } } else if ("rhombus".equals(form)) { cnt_f5 += 1; if("red".equals(color)) { cnt_f5c1 += 1; } else if ("blue".equals(color)) { cnt_f5c2 += 1; } else if ("yellow".equals(color)) { cnt_f5c3 += 1; } else if ("black".equals(color)) { cnt_f5c4 += 1; } else if ("white".equals(color)) { cnt_f5c5 += 1; } } if("red".equals(color)) { cnt_c1 += 1; } else if ("blue".equals(color)) { cnt_c2 += 1; } else if ("yellow".equals(color)) { cnt_c3 += 1; } else if ("black".equals(color)) { cnt_c4 += 1; } else if ("white".equals(color)) { cnt_c5 += 1; } } model.addAttribute("cnt_f1", cnt_lb1); model.addAttribute("cnt_f2", cnt_lb2); model.addAttribute("cnt_f3", cnt_lb3); model.addAttribute("cnt_f4", cnt_lb4); model.addAttribute("cnt_f5", cnt_lb5); model.addAttribute("cnt_f1c1", cnt_f1c1); model.addAttribute("cnt_f1c2", cnt_f1c2); model.addAttribute("cnt_f1c3", cnt_f1c3); model.addAttribute("cnt_f1c4", cnt_f1c4); model.addAttribute("cnt_f1c5", cnt_f1c5); model.addAttribute("cnt_f2c1", cnt_f2c1); model.addAttribute("cnt_f2c2", cnt_f2c2); model.addAttribute("cnt_f2c3", cnt_f2c3); model.addAttribute("cnt_f2c4", cnt_f2c4); model.addAttribute("cnt_f2c5", cnt_f2c5); model.addAttribute("cnt_f3c1", cnt_f3c1); model.addAttribute("cnt_f3c2", cnt_f3c2); model.addAttribute("cnt_f3c3", cnt_f3c3); model.addAttribute("cnt_f3c4", cnt_f3c4); model.addAttribute("cnt_f3c5", cnt_f3c5); model.addAttribute("cnt_f4c1", cnt_f4c1); model.addAttribute("cnt_f4c2", cnt_f4c2); model.addAttribute("cnt_f4c3", cnt_f4c3); model.addAttribute("cnt_f4c4", cnt_f4c4); model.addAttribute("cnt_f4c5", cnt_f4c5); model.addAttribute("cnt_f5c1", cnt_f5c1); model.addAttribute("cnt_f5c2", cnt_f5c2); model.addAttribute("cnt_f5c3", cnt_f5c3); model.addAttribute("cnt_f5c4", cnt_f5c4); model.addAttribute("cnt_f5c5", cnt_f5c5); model.addAttribute("cnt_c1", cnt_c1); model.addAttribute("cnt_c2", cnt_c2); model.addAttribute("cnt_c3", cnt_c3); model.addAttribute("cnt_c4", cnt_c4); model.addAttribute("cnt_c5", cnt_c5); model.addAttribute("cnt_all", record);

return result;

}

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jimbe

2019/09/27 03:50

> 動作できることは確認済み コンパイルエラーになっています.
guest

回答4

0

主題から少しずれてしまうかもしれませんが
処理が長くなっている原因は集計をJava側でやっているからというのもありますね
こういう集計はSQLに任せる方がそれっぽくまとまると思います

投稿2019/09/27 03:10

q_sane_q

総合スコア610

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

一番単純なのは配列を使うことです。各文字列から格納すべき場所を決定し、その場所のカウントを1増やす、という方法を繰り返します。

java

1List<String> shapes = Arrays.asList("circle", "triangle", "square", "ellipse", "rhombus"); 2List<String> colors = Arrays.asList("red", "blue", "yellow", "black", "white"); 3int[][] counts = new int[colors.size() + 1][shapes.size() + 1]; 4for(Table1Entity entity : table1DataList) { 5 int colomn = shapes.indexOf(entity.getForm()); 6 int row = colors.indexOf(entity.getColor()); 7 8 counts[row][column]++; 9 counts[row][shapes.size()]++; 10 counts[colors.size()][column]++; 11}

対応が見えにくい、という場合は、Mapをネストして使うという方法も考えられます。

投稿2019/09/27 01:50

swordone

総合スコア20651

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

form X colorすべての組み合わせを表に集計

formの一覧、colorの一覧をプログラムで固定せず、データベースから読み込んだデータを利用します。
form X colorの組み合わせをすべて揃えるために、Table1Entityに度数(freq)フィールドを追加します。freqの値は次のように設定。

  • 1 データベースから読み込んだデータ
  • 0 初期値データ(ダミー)

Java

1public class Table1Entity { 2 private String form; 3 private String color; 4 int freq; // 1 データベースから読み込み、 0 初期値として作成

form名のヘダーデータ(昇順)。プログラム定数を持たずデータベースのデータを利用。

Java

1// from ヘダー : 文字列昇順 2Set<String> formHeader = table1DataList.stream() 3 .map(Table1Entity::getForm) 4 .collect(Collectors.toCollection(TreeSet::new)); 5System.out.println(formHeader);

color名のヘダーデータ(昇順)。プログラム定数を持たずデータベースのデータを利用。

Java

1// color ヘダー : 文字列昇順 2Set<String> colorHeader = table1DataList.stream() 3 .map(Table1Entity::getColor) 4 .collect(Collectors.toCollection(TreeSet::new)); 5System.out.println(colorHeader);

form X color の直積 (ダミー) 表。度数 0 の一覧。

Java

1// form X color の直積 (0カウンター) 2Stream<Table1Entity> initialCounters = colorHeader.stream() 3 .flatMap(e -> formHeader.stream() 4 .map(f -> new Table1Entity(f, e, 0)));

直積 (ダミー) 表とデータベースのデータを併合して集計します。Table1Entity.freqを加算することで度数を求めます。

Java

1// 度数集計 2Map<String,Map<String,Long>> freqs = 3 Stream.concat(table1DataList.stream(),initialCounters) 4 .collect(Collectors.groupingBy( 5 Table1Entity::getColor, 6 TreeMap::new, 7 Collectors.groupingBy( 8 Table1Entity::getForm, 9 TreeMap::new, 10 Collectors.summingLong(Table1Entity::getFreq)) // 度数を加算 11)); 12System.out.println(freqs); 13System.out.println(freqs.values().stream().map(e -> e.values()).collect(Collectors.toList()));

度数集計を示すだけで、列集計、行集計はしていません。

投稿2019/10/03 10:42

xebme

総合スコア1081

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

xebme

2019/10/03 10:44

すっきりだろうか?これはまだ冗長かもしれません。
guest

0

スッキリの基準は人それぞれですので, どこまでやれば良いのかは判断できませんが.
ランダムに10件のデータを用意して集計しています.
一応 model.addAttribute まで行うようにしましたが, 無いデータ(=0件)分は行っていません.

java

1import java.util.*; 2 3public class Q214024 { 4 private static final List<String> FORMS = Arrays.asList("circle","triangle","square","ellipse","rhombus"); 5 private static final List<String> COLORS = Arrays.asList("red","blue","yellow","black","white"); 6 private static final String KEY_SEPARATOR = ":"; 7 8 private String getAttributeName(String form, String color) { 9 if(form.isEmpty() && color.isEmpty()) return "cnt_all"; 10 StringBuilder name = new StringBuilder("cnt_"); 11 if(!form.isEmpty() ) name.append("f").append(FORMS.indexOf(form) +1); 12 if(!color.isEmpty()) name.append("c").append(COLORS.indexOf(color)+1); 13 return name.toString(); 14 } 15 16 private String getDB(Model model){ 17 List<Table1Entity> table1DataList = table1Repository.findAll(); 18 19 //集計 20 Map<String,Integer> map = new HashMap<>(); 21 for (Table1Entity entity : table1DataList) { 22 String form = entity.getForm(); 23 String color = entity.getColor(); 24 for(String key : Arrays.asList(form+KEY_SEPARATOR+color,form+KEY_SEPARATOR,KEY_SEPARATOR+color)) { 25 map.put(key, map.containsKey(key) ? map.get(key)+1 : 1); 26 } 27 } 28 map.put(KEY_SEPARATOR, table1DataList.size()); 29 30 //設定 31 for(Map.Entry<String, Integer> entry : map.entrySet()) { 32 String[] keys = entry.getKey().split(KEY_SEPARATOR); 33 String form = keys.length >= 1 ? keys[0] : ""; 34 String color = keys.length >= 2 ? keys[1] : ""; 35 model.addAttribute(getAttributeName(form, color), entry.getValue()); 36 } 37 38 return ""+table1DataList.size(); 39 } 40 41 // 以下テスト用 42 private Table1Repository table1Repository = new Table1Repository(); 43 void add(String form, String color) { 44 table1Repository.add(form, color); 45 } 46 void printAll() { 47 table1Repository.printAll(); 48 } 49 static class Model { 50 void addAttribute(String name, int value) { 51 System.out.println("name="+name+", value="+value); 52 } 53 } 54 static class Table1Entity { 55 private String form, color; 56 Table1Entity(String form, String color) { this.form=form; this.color=color; } 57 String getForm(){ return form; } 58 String getColor() { return color; } 59 public String toString() { return form+":"+color; } 60 } 61 static class Table1Repository { 62 private List<Table1Entity> list = new ArrayList<Table1Entity>(); 63 void add(String form, String color) { 64 list.add(new Table1Entity(form, color)); 65 } 66 List<Table1Entity> findAll() { 67 return list; 68 } 69 void printAll() { 70 for(Table1Entity entity : list) System.out.println(entity); 71 } 72 } 73 74 public static void main(String args[]) { 75 Q214024 q214024 = new Q214024(); 76 Random random = new Random(); 77 for(int i=0; i<10; i++) { 78 q214024.add(FORMS.get(random.nextInt(FORMS.size())), COLORS.get(random.nextInt(COLORS.size()))); 79 } 80 q214024.printAll(); 81 System.out.println("----"); 82 q214024.getDB(new Model()); 83 } 84}

plain

1rhombus:white 2ellipse:black 3triangle:white 4square:red 5rhombus:white 6ellipse:white 7triangle:black 8triangle:yellow 9triangle:black 10rhombus:white 11---- 12name=cnt_f4, value=2 13name=cnt_f3, value=1 14name=cnt_f5, value=3 15name=cnt_f2c5, value=1 16name=cnt_f5c5, value=3 17name=cnt_f2, value=4 18name=cnt_c1, value=1 19name=cnt_c3, value=1 20name=cnt_f4c5, value=1 21name=cnt_f2c3, value=1 22name=cnt_f2c4, value=2 23name=cnt_c4, value=3 24name=cnt_f4c4, value=1 25name=cnt_f3c1, value=1 26name=cnt_c5, value=5 27name=cnt_all, value=10

全ての Attribute を設定するため, 集計をクラス化してみました.
form/color を enum にし, 異常値を弾くようにしました.

java

1import java.util.*; 2 3public class Q214024_2 { 4 5 enum Form { 6 circle, triangle, square, ellipse, rhombus, total; 7 static int size() { return Form.values().length; } 8 //テスト用 9 static Form getValue(Random random) { 10 return Form.values()[random.nextInt(Form.total.ordinal())]; 11 } 12 }; 13 enum Color { 14 red, blue, yellow, black, white, total; 15 static int size() { return Color.values().length; } 16 //テスト用 17 static Color getValue(Random random) { 18 return Color.values()[random.nextInt(Color.total.ordinal())]; 19 } 20 }; 21 22 //集計テーブル 23 private static class SummaryTable { 24 private int[][] values; //件数 25 SummaryTable() { 26 values = new int[Form.size()][Color.size()]; 27 for(int i=0; i<values.length; i++) 28 for(int j=0; j<values[i].length; j++) 29 values[i][j] = 0; 30 } 31 //form,colorの件数を +1 する 32 void increment(Form form, Color color) { 33 values[form.ordinal()][color.ordinal()] ++; 34 } 35 //(Model に設定する) Attribute と件数のマップを返す 36 Map<String,Integer> getAttributeMap() { 37 calcTotals(); 38 Map<String,Integer> map = new HashMap<>(); 39 for(Form form : Form.values()) { 40 for(Color color : Color.values()) { 41 map.put(getAttributeName(form,color), values[form.ordinal()][color.ordinal()]); 42 } 43 } 44 return map; 45 } 46 //各合計を計算 47 private void calcTotals() { 48 for(int j=0; j<Color.size(); j++) values[Form.total.ordinal()][j] = 0; 49 for(int i=0; i<Form.size(); i++) { 50 values[i][Color.total.ordinal()] = 0; 51 for(int j=0; j<Color.total.ordinal(); j++) { 52 values[i][Color.total.ordinal()] += values[i][j]; 53 if(i != Form.total.ordinal()) values[Form.total.ordinal()][j] += values[i][j]; 54 } 55 } 56 } 57 //Attribute 名を返す 58 private String getAttributeName(Form form, Color color) { 59 if(form == Form.total && color == Color.total) return "cnt_all"; 60 StringBuilder name = new StringBuilder("cnt_"); 61 if(form != Form. total) name.append("f").append(form.ordinal() +1); 62 if(color != Color.total) name.append("c").append(color.ordinal()+1); 63 return name.toString(); 64 } 65 } 66 67 private String getDB(Model model){ 68 List<Table1Entity> table1DataList = table1Repository.findAll(); 69 70 //集計 71 SummaryTable table = new SummaryTable(); 72 for (Table1Entity entity : table1DataList) { 73 try { 74 Form form = Form.valueOf(entity.getForm()); 75 Color color = Color.valueOf(entity.getColor()); 76 table.increment(form, color); 77 } catch(IllegalArgumentException e) { 78 System.err.println("form または color の値が異常です. form="+entity.getForm()+", color="+entity.getColor()); 79 } 80 } 81 82 //設定 83 for(Map.Entry<String, Integer> entry : table.getAttributeMap().entrySet()) { 84 model.addAttribute(entry.getKey(), entry.getValue()); 85 } 86 87 return ""+table1DataList.size(); 88 } 89 90 // 以下テスト用 91 private Table1Repository table1Repository = new Table1Repository(); 92 void add(String form, String color) { 93 table1Repository.add(form, color); 94 } 95 void printAll() { 96 table1Repository.printAll(); 97 } 98 static class Model { 99 void addAttribute(String name, int value) { 100 System.out.println("name="+name+", value="+value); 101 } 102 } 103 static class Table1Entity { 104 private String form, color; 105 Table1Entity(String form, String color) { this.form=form; this.color=color; } 106 String getForm(){ return form; } 107 String getColor() { return color; } 108 public String toString() { return form+":"+color; } 109 } 110 static class Table1Repository { 111 private List<Table1Entity> list = new ArrayList<Table1Entity>(); 112 void add(String form, String color) { 113 list.add(new Table1Entity(form, color)); 114 } 115 List<Table1Entity> findAll() { 116 return list; 117 } 118 void printAll() { 119 for(Table1Entity entity : list) System.out.println(entity); 120 } 121 } 122 123 public static void main(String args[]) { 124 Q214024_2 q214024 = new Q214024_2(); 125 126 Random random = new Random(); 127 for(int i=0; i<10; i++) { 128 q214024.add(Form.getValue(random).name(), Color.getValue(random).name()); 129 } 130 //q214024.add("zzz", Color.getValue(random).name()); 131 q214024.printAll(); 132 133 System.out.println("----"); 134 q214024.getDB(new Model()); 135 } 136}

投稿2019/09/27 05:02

編集2019/09/27 12:18
jimbe

総合スコア12634

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問