Home > OS >  How do I write for-loop statements in streams?
How do I write for-loop statements in streams?

Time:07-27

Map<String, Price> response = new HashMap<>();

    for(int i=0; i<price.getData().size(); i  ){
        for(int j=0; j<exchangeRates.getData().size(); j  ){
            if(priceOutput.getData().get(i).getTodayDate().isEqual(exchangeRates.getData().get(j).getTodayDate())){
                response.put(price.getData().get(i).getId(), price.getData().get(i));
            }
        }
    }
return response;

I have written this logic using for-loops statements,

Now how do I write the same piece of code using streams?

CodePudding user response:

You can use Stream#anyMatch to filter based on another list. Something like this(not tested since I don't have the POJO)

List<Price> list1 = price.getData();
List<AnotherPojo> list2 =  exchangeRates.getData();

Map<String, Price> response = list1.stream()
                                    .filter(p -> list2.stream().anyMatch(e -> e.getTodayDate().isEqual(p.getTodayDate())))
                                    .collect(Collectors.toMap(p -> s1.getId(), p->p))

working test example:

List<String> list1 = Arrays.asList("A1", "B1", "C1", "D1");
List<String> list2 = Arrays.asList("A2", "B1", "C2", "D1");

Map<String, String> map = list1.stream()
    .filter(s1 -> list2.stream().anyMatch(s2 -> s2.equals(s1)))
    .collect(Collectors.toMap(s1 -> s1, s1 -> s1));

//output  {D1=D1, B1=B1}

CodePudding user response:

list.stream().foreach( currentElementAsVariable-> {
    // some logic and/or open other foreach if needed
})

You can use single statements directly and using { } you can open a real multi-line block of code.

  •  Tags:  
  • java
  • Related