I need little help - I have one method where my for loop needs to be changed to use java 8 stream | Core Java Forum
A
Asim Toor Posted on 28/08/2021

Hi,

Please bold for loop need to be changed to use stream, what I mean to say instead of using .keyset, need something like the follwoing:

validations
.entrySet()
.stream()
.forEach(
entry -> {
String value = entry.getValue(); ..........


Why:
String thekey : validations.keySet() for loop does not go through sonarQube in my coding

----------------------- ********************** ----------------------- **********************

public static ValidationErrorProblemType createValidationErrors(
Map<String, List<String>> validations) throws URISyntaxException {
ValidationErrorProblemType validationErrorProblemType = new ValidationErrorProblemType();
URI validationUri = new URI(URL);
List<ValidationErrorProblemTypeAllOfViolations> validationErrorProblemTypeAllOfViolationsList =
new ArrayList<>();


for (String thekey : validations.keySet()) {
List<String> values = validations.get(thekey);
ValidationErrorProblemTypeAllOfViolations validationErrorProblemTypeAllOfViolations =
new ValidationErrorProblemTypeAllOfViolations();
validationErrorProblemTypeAllOfViolations.setReason(thekey);
validationErrorProblemTypeAllOfViolations.setInvalidParams(values);
if (!values.isEmpty()) {
validationErrorProblemTypeAllOfViolationsList.add(
validationErrorProblemTypeAllOfViolations);
}
}
validationErrorProblemType.setViolations(validationErrorProblemTypeAllOfViolationsList);
validationErrorProblemType.setTitle("Validation Error");
validationErrorProblemType.setStatus(400);
validationErrorProblemType.setType(validationUri);
validationErrorProblemType.setBookmark("EAIP_Benefits");
return validationErrorProblemType;
}


------------------ ********************** ----------------------- ********************** -----------------------
data class ValidationErrorProblemType (

@JsonProperty("tp") var tp: java.net.URI? = null,


@JsonProperty("ttl") var ttl: kotlin.String? = null,

@get:Min(100)
@get:Max(600)

@JsonProperty("sts") var sts: kotlin.Int? = null,


@JsonProperty("dtl") var dtl: kotlin.String? = null,


@JsonProperty("inst") var inst: java.net.URI? = null,


@JsonProperty("citExt") var cidExt: kotlin.String? = null,


@JsonProperty("text") var text: kotlin.String? = null,


@JsonProperty("violations") var violations: kotlin.collections.List<ValidationErrorProblemTypeAllOfViolations>? = null,


@JsonProperty("faults") var faults: kotlin.collections.List<StatusMessage>? = null
) {
constructor() : this(null, null, null, null, null, null, null, null, null)

}

------------------ ********************** ----------------------- ********************** -----------------------


M
Replied on 28/08/2021

Run this code. It will help you understand what you need to do. In case you could not get anything or could not implement your logic, please let me know:

 

package com.programming.class12;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
    
    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

}
public class ForAndStream {

	private static List<String> forLoop1(List<Person> persons) {
		//List.of() to create immutable data.
	    //persons = List.of();
	    List<String> result = new ArrayList<>();
	    for(Person p : persons){
	        if(p.getAge() > 18){
	            result.add(p.getName());
	        }
	    }
	    return result;
	}
	
	//Conclusion: filter → decides if a value is correct, map → Transforms 1 value to another
	//and collect() function to concatenate the list elements.
	private static List<String> streaming1(List<Person> persons) {
		//persons = List.of();
	    List<String> result = persons.stream()
	            .filter(p -> p.getAge() > 18)
	            .map(p -> p.getName())
	            .collect(Collectors.toList());
	    return result;
	
	}
	
	//Given a list of Persons, give me the names of everyone who is between 19 and 65 whose 
	//name is not null and starts with a 'D'
	private static List<String> forLoop2(List<Person> persons){
	    //persons = List.of();
	    List<String> result = new ArrayList<>();

	    for(Person p : persons){
	        if(p.getAge() > 18 && p.getAge() <= 65 && p.getName() != null && p.getName().startsWith("D")){
	            result.add(p.getName());
	        }
	    }
	    return result;
	}
	
	// same using stream
	//Conclusion: filter → decides if a value is correct, map → Transforms 1 value to another
	//and collect() function to concatenate the list elements.
	private static List<String> streaming2(List<Person> persons) {
		//persons = List.of();
		List<String> result = persons.stream()
            .filter(p -> p.getAge() > 18)
            .filter(p -> p.getAge() <= 65)
            .filter(p -> p.getName() != null)
            .filter(p -> p.getName().startsWith("D"))
            .map(p -> p.getName())
            .collect(Collectors.toList());
		return result;
	}
	
	public static void main(String[] args) {
		
		List<Person> list = new ArrayList<>();
		Person p1 = new Person("A", 15);
		Person p2 = new Person("B", 17);
		Person p3 = new Person("C", 19);
		Person p4 = new Person("D", 21);
		
		list.add(p1);list.add(p2);list.add(p3);list.add(p4);
		
		List<String> output = null;
		output = forLoop1(list);
		Iterator<String> itr = output.iterator();
		while(itr.hasNext()) {
			System.out.print(itr.next() + " ");
		}
		System.out.println();
		output = streaming1(list);
		itr = output.iterator();
		while(itr.hasNext()) {
			System.out.print(itr.next() + " ");
		}
		
		System.out.println();
		output = forLoop2(list);
		for(int i = 0; i < output.size(); i++) {
			System.out.println(output.toString());
		}
		output = streaming2(list);
		for(int i = 0; i < output.size(); i++) {
			System.out.println(output.toString());
		}
		//System.out.println("No Result");
		
		streamWithMap();
	}
	
	private static void streamWithMap() {
		Map<Integer, String> map = new HashMap<>();
		map.put(114, "A");
		map.put(99, "B");
		map.put(201, "C");
		map.put(4, "D");
		map.put(299, "E");

		System.out.println("--- Unsorted Map ---");
		System.out.println(map);

		System.out.println("--- Sorted Map (Sorted by Key) ---"); 
		map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(System.out::println); // :: is method reference

		// Another way to sort a Map by keys // :: is method reference
		System.out.println("--- Sorted Map (Sorted by Key) ---");
		map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).forEach(System.out::println);
		
		//Or Simply like this:
		map.entrySet().forEach(entry -> {
		    System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
		}); 
	}
}