java8-Collections and Streams

stream和集合的區別是什麼?api

1.在計算的時候處理不一樣,app

2.every element should be computed in the memory and then to be part of collectionsspa

stream.net

 

Stream apis

filter with a predicate ,Filtering unique elements in a stream,using filter distinct skip limitorm

 

map and flatmapip

 

Finding and matching:findFirst findAny allMatch,noneMatch,anyMatchci

 

Reducingelement

 

Eg:get

@Test
public void test() {
    List<Dish> dishList =
new ArrayList<>();
    Dish dish1 =
new Dish("dish1", true, 1, Dish.Type.FISH);
    Dish dish2 =
new Dish("dish2", false, 1, Dish.Type.OTHER);
    Dish dish3 =
new Dish("dish3", true, 1, Dish.Type.OTHER);
    Dish dish4 =
new Dish("dish4", false, 1, Dish.Type.FISH);
    dishList.add(dish1);
    dishList.add(dish2);
    dishList.add(dish3);
    dishList.add(dish4);
    dishList.stream().filter(Dish::isVegetarian).limit(
1).collect(toList()).forEach(System.out::println);
    dishList.stream().filter(Dish::isVegetarian).collect(toList()).forEach(System.
out::println);
    dishList = dishList.stream().filter(d -> (d.getType().equals(Dish.Type.
FISH))).collect(toList());

    dishList.forEach(s -> System.
out.println(s.getName()));

    List<String> words = Arrays.asList(
"Java8", "Lambdas", "in", "action");
    List<Integer> wordLengths = words.stream().map(String::length)
            .collect(toList());

List<Integer> dishNameLengths = dishList.stream().map(Dish::getName).map(String::length).collect(toList());
   
//Arrays::stream()
    //flatMap using flatmap to find the unique characters from  a list of words
   
List<String> uniqueCharacters = words.stream().map(w -> w.split("")).flatMap(Arrays::stream)
            .distinct().collect(Collectors.toList());

   
//mapping matching least one
   
if (dishList.stream().anyMatch(Dish::isVegetarian)) {
        System.
out.printf("The menu is vegetarian friendly!");
    }
   
//matching all <>nonematching

   
if (dishList.stream().allMatch(Dish::isVegetarian)) {
        System.
out.printf("The menu is vegetarian friendly!");
    }


    dishList.stream().map(d ->
1).reduce(0, (a, b) -> a + b);

   
//sum.min,max,.average()
    //OptionalDouble

   
OptionalDouble sumCalories = dishList.stream().mapToInt(Dish::getCalories).average();
    IntStream intStream=dishList.stream().mapToInt(Dish::getCalories);

    Stream<Integer> stream=intStream.boxed();

   
//numeric rangdes  on IntStream and longStream to generate such ranges :range and reangelosed

  
IntStream evenNumbers= IntStream.rangeClosed(1,100).filter(n->n%2==0);
    System.
out.println(evenNumbers.count());
   
// stream from string
    //stream from int
    //stream from functions
string

 


    @Test
   
public void test() {
        Trader raoul =
new Trader("Raoul", "Cambridge");
        Trader mario =
new Trader("Mario", "Milan");
        Trader alan =
new Trader("Alan", "Cambridge");
        Trader brian =
new Trader("Brian", "Cambridge");
        List<Transaction> transactions = Arrays.asList(
new Transaction(brian, 2011, 300)
                ,
new Transaction(raoul, 2012, 1000),
               
new Transaction(raoul, 2011, 400),
               
new Transaction(mario, 2012, 710),
               
new Transaction(raoul, 2012, 700),
               
new Transaction(alan, 2012, 950)
        );


       
//find all transactions in 2011 and sort by value(small to high)

       
List<Transaction> tr2011 = transactions.stream().filter(transaction -> transaction.getYear() == 20111)
                .sorted(Comparator.comparing(Transaction::getValue)).collect(toList());
       
//what are all the unique cities where the traders work?

       
List<String> cities = transactions.stream().map(transaction -> transaction.getTrader().getCity()).distinct().collect(toList());

       
//above one is equals below
       
Set<String> cities1 = transactions.stream().map(transaction -> transaction.getTrader().getCity()).collect(toSet());

       
//find all traders form cambridge  and sort them by name
       
List<Trader> traders = transactions.stream().map(Transaction::getTrader).filter(trader -> (trader.getCity().equals("Cambridge"))).distinct().sorted(Comparator.comparing(Trader::getName)).collect(toList());

//return a string of all traders' names sorted alphavetically
       
String traderStr = transactions.stream().map(transaction -> transaction.getTrader().getName()).distinct().sorted().reduce("", (n1, n2) -> n1 + n2);
        String traderStr1 = transactions.stream().map(transaction -> transaction.getTrader().getName()).distinct().sorted().collect(joining());

//are any traders based in Milan?

       
boolean milanBased = transactions.stream().anyMatch(transaction -> transaction.getTrader().getCity().equals("Milan"));
       
//print all transactions' values form the traders living in Cambridge
       
transactions.stream().filter(t->"Cambridge".equals(t.getTrader().getCity())).map(Transaction::getValue).forEach(System.out::println);

      
// whats't the highest value of all the transactions?
       
Optional<Integer> highestValue=transactions.stream().map(Transaction::getValue).reduce(Integer::max);
//find the trnasction with the smallest value
       
Optional<Transaction> smallestTransaction=transactions.stream().reduce((t1,t2)->t1.getValue()<t2.getValue()?t1:t2);

        Optional<Transaction> smallestTransaction1=transactions.stream().min(Comparator.comparing(Transaction::getValue));

       
//Numneric streams
        //IntStream, LongStream, DoubleStream mapToint mapToDouble mapToLong






   
}

 

 

    public void test(){

    List<Integer> numbers=
new ArrayList<>();
   
int sum=0;
   
for(int i:numbers){
        sum+=i;
    }
   
//reduce :two arguments   an initial vaule 0;
   
sum=numbers.stream().reduce(0,(a,b)->a+b);
    sum=numbers.stream().reduce(
0,Integer::sum);

   
//reduce find the max member
   
Optional<Integer> max=numbers.stream().reduce(Integer::max);
   
//reduce find the min member
   
Optional<Integer> min=numbers.stream().reduce(Integer::min);
    numbers.parallelStream().reduce(
0,Integer::sum);

}

 

如何將List<String>轉成List<Long>

List<Long> gids = Arrays.asList(groupIds.split(",")).stream().map(gid->Long.parseLong(gid)).collect(Collectors.toList());
相關文章
相關標籤/搜索