- map、forEach、mapToInt的用法示例
package com.yf.stream;
import com.yf.po.Animal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.crypto.spec.PSource;
import org.junit.Before;
import org.junit.Test;
public class TestStream {
List<Animal> list = new ArrayList<Animal>();
@Before
public void boforre(){
Animal animal1 = new Animal("老虎","虎头","4条腿");
Animal animal2 = new Animal("狮子","虎头","4条腿");
Animal animal3 = new Animal("雄鹰","虎头","4条腿");
Animal animal4 = new Animal("鳄鱼","虎头","4条腿");
Animal animal5 = new Animal("猴子","虎头","4条腿");
list.add(animal1);
list.add(animal2);
list.add(animal3);
list.add(animal4);
list.add(animal5);
}
@Test
public void testMap(){
List<String> names = list.stream().map(Animal::getName)
.collect(Collectors.toList());
System.out.println(names);
System.out.println("开始测试");
list.stream().map(animal -> {
if(animal.getName().equals("狮子")){
animal.setName("平原上我是最无敌的");
}
System.out.println(animal);
return animal;
}).collect(Collectors.toList());
System.out.println(list);
}
@Test
public void testForEach(){
list.stream().forEach(a ->{
if(a.getName().equals("老虎")){
a.setName(a.getName()+"森林之王威武==");
}
}
);
System.out.println(list);
}
@Test
public void testMapToint(){
List<Integer> integers = Arrays.asList(1, 2, 3, 4);
List<String> strings = Arrays.asList("张三11", "李四222", "王五3333");
int sum = strings.stream().mapToInt(s -> s.length()).sum();
System.out.println(integers);
System.out.println(sum);
}
}