1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Java の static method でも型変数を使いたい!

Posted at

「メソッドスコープでの型宣言」というらしい。
「static method 型変数」とかググっても、上記の言葉でググっても普通の変数のスコープの話とか「static method とはなにか」とかしか出て来ず、twitterで直接教えてもらって初めて知ったので似たような悩みを抱えてる人はきっといると思う

発端

~ツイッターにて~

自分『Javaで List の中身一括変換するのに foreach とかするのダルくない?? map とか無いの???みんなどうやってるの???』 ← List のメソッドだけ見て map 関数が無いからキレてる

心優しい人「Javaにも map あるで!」

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

// 中略

Integer[] iArray = { 1, 2, 3, 4, 5 };
List<Integer> iList = Arrays.asList(iArray);
List<String> sList = iList.stream().map(i -> i.toString()).collect(Collectors.toList());

// 後略

長え!!!!校長先生の話ぐらいには長え!!!!

で、

『適当にユーティリティクラス作るか……』

public class Util {
  public static List<S> map(List<T> l, Function<T, S> f) {
    return l.stream().map(f).collect(Collectors.toList());
  }
}
T cannot be resolved to a typeJava(16777218)
S cannot be resolved to a typeJava(16777218)

\デデーン/

『qあwsえdrftgyふじこlp;@:「」』

心優しい人2「メソッドスコープに型宣言ができるんやで」

public class Util {
  public static <S, T> List<S> map(List<T> l, Function<T, S> f) {
    //          ^^^^^^ これ!!!!
    return l.stream().map(f).collect(Collectors.toList());
  }
}

なるほどぉぉぉぉぉぉ……なるほどぉぉぉぉ………知らんかった……

……JavaにもJSのunderscoreみたいなライブラリないかな……ばなな……

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?