2

I would like to know how do I convert the following lambda expression to a for-each loop:

private static List<GrantedAuthority> mapToGrantedAuthorities(List<Authority> authorities) {
    return authorities.stream()
            .map(authority -> new SimpleGrantedAuthority(authority.getName().name()))
            .collect(Collectors.toList());
}
2
  • 3
    Why do you want to do that? Commented Oct 17, 2016 at 12:50
  • 1
    Because Im using JAVA 1.6 Commented Oct 17, 2016 at 12:52

3 Answers 3

4

That should work:

List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
for(Authority auth : authorities)
    list.add(new SimpleGrantedAuthority(auth.getName().name()));
return list;

I guess you are using java lower than 1.8, that's why you want to do that, it's probably faster too.

Sign up to request clarification or add additional context in comments.

Comments

0

You could also use Google Guava (https://github.com/google/guava) to get somewhat closer to the Java 8 style in previous Java versions:

private static List<GrantedAuthority> mapToGrantedAuthorities(final List<Authority> authorities) {
    return Lists.transform(authorities, new Function<Authority,GrantedAuthority>(){
        @Override
        public GrantedAuthority apply(Authority authority) {
            return new SimpleGrantedAuthority(authority.getName().name());
        }
    });
}

Comments

0

The basis of Lambda Expressions is that the Lambda takes a class with one method only, in this case it is doing a foreach loop with the stream, and is creating a new SimpleGrantedAuthority using the name from the list being passed in and then returning another list of authorities.

So it is taking a list of Authorities and returning the same List but as GrantedAuthorities.

List<GrantedAuthority> granted = new ArrayList<GrantedAuthority>();
for( Authority auth : authorities)
{
    granted.add(new SimpleGrantedAuthority(auth.getName().name()));
}
return granted;

2 Comments

May be I am just misunderstanding the first sentence of your answer, but Lambda Expressions can take an arbitrary number of parameters.
Sorry i didnt make myself clear, Most simple Lambda calls rely on Functional Interfaces, a functional interface has exactly one abstract method. - i confused methods and parameters, sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.