Skip to content

Instantly share code, notes, and snippets.

@pandanote-info
Created May 22, 2021 14:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pandanote-info/937d799a64e7a2efd125e0b815f15968 to your computer and use it in GitHub Desktop.
Save pandanote-info/937d799a64e7a2efd125e0b815f15968 to your computer and use it in GitHub Desktop.
配列の配列の要素数の総和を求めるメソッドをJava8のラムダ式を使わない場合と使った場合の2通りの方法で書いたプログラム。
package info.pandanote.test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class CountElement {
public static void test1(Map<Integer,Set<Integer>> a) {
int count = 0;
for (Entry<Integer,Set<Integer>> e: a.entrySet()) {
count += e.getValue().size();
}
System.out.println(count);
return;
}
public static void test2(Map<Integer,Set<Integer>> a) {
System.out.println(a.entrySet().stream().mapToInt(e -> e.getValue().size()).sum());
}
public static void main(String args[]) {
Map<Integer,Set<Integer>> a = new HashMap<Integer,Set<Integer>>();
a.put(1,new HashSet<Integer>(Arrays.asList(1,2,3,4,5)));
a.put(2,new HashSet<Integer>(Arrays.asList(1,2)));
a.put(3,new HashSet<Integer>(Arrays.asList(1,2,6,7,8,9)));
test1(a);
test2(a);
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment