最近遇到lambda 的表达式,总结了一下,,用一个稍微复杂的小例子 总结一下
public class streamTest {
@Test
public void lambdaTest() {
final Function<Object, String> mValOrEmpty = (val) -> (val == null ? “” : val.toString());
// given
Map<String,Integer> map1=new HashMap<>();
map1.put(“1”, 2);
map1.put(“2”, 3);
map1.put(“3”, 4);
map1.put(“4”, 5);
Map<String,Integer> map2=new HashMap<>();
map2.put(“3”, 4);
map2.put(“5”, 6);
map2.put(“7”, 8);
map2.put(“9”, 10);
Set<String> set4=getSum1(map2);
System.out.println(“取出k+v>10 的元素并返回对应的k:”+set4);
List<Map<String,Integer>> list = new ArrayList<>();
list.add(map1);
list.add(map2);
// 遍历map集合的元素
list.stream().forEach(map -> map.forEach((k,v) -> System.out.println(“key:value = “ + k + “:” + v)));
//(1)采用forEach+if 的条件判断来实现
list.stream()
.forEach(map -> map.forEach((k,v)->{
if((v+Integer.valueOf(k))>10){
System.out.println(“符合条件的k:v =” +k+“:”+ v);
}
}));
//(2) 调用判断方法来实现
list.stream()
.filter( map -> getSum(map) )
.forEach( map -> map.forEach( (k,v) -> System.out.println(“key:value = “ + k + “:” + v)) );
// List<Integer> ints1 = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10);
// System.out.println(“ints sum is:” + ints1.stream().reduce(1, (sum, item) -> sum + item));//1+1+2+3+4+…
}
//判断map中所有元素的k+v+k+v… 的总和是否>10
public boolean getSum(Map<String, Integer> map1) {
Set<Entry<String,Integer>> set=map1.entrySet();
int sum=0;
for(Entry entry:set){
String key=entry.getKey().toString();
String value=entry.getValue().toString();
sum+=Integer.valueOf(key)+Integer.valueOf(value);
}
if(sum>10){
return true;
}
return false;
}
//取出k+v>10 的元素并返回对应的k
public Set<String> getSum1(Map<String, Integer> map1) {
Set<String> set=map1.keySet();
Set<String> set1=set.stream().filter(key ->((Integer.valueOf(key)+map1.get(key).intValue())>10)).collect(Collectors.toSet());
return set1;
}
@Test
public void listTest(){
List<String> items = new ArrayList<>();
items.add(“A”);
items.add(“B”);
items.add(“C”);
items.add(“D”);
items.add(“E”);
items.stream()
.filter(s->s.equals(“B”))
.forEach(System.out::println);
}
}