2

How can i change following code using java 8 lambda expressions. Below is my code:

public class Main {
class Student {
            String name;
            int mark;
            String parentName; 

            public String getName() {
                return name;
            }
            public int getMark() {
                return mark;
            }
            public String getParentName() {
                return parentName;
            }
        }

        class Empl {
            String name;
            long salary;
            String managerName;

            public String getName() {
                return name;
            }
            public long getSalary() {
                return salary;
            }
            public String getManagerName() {
                return managerName;
            }
        }

        public static void main(String[] args) {
            List<Student> list1 = new ArrayList<>();
            List<Empl> list2 = new ArrayList<>();
            // Storing data to list1 and list2
            List<String> result = new ArrayList<>();
            for(Student s :list1) {
                result.add(s.getName());
                result.add(s.getParentName());
            }
            for(Empl m :list2) {
                result.add(m.getName());
                result.add(m.getManagerName());
            }
            System.out.println(result);     
        }
    }

In the above code i have used for loops for adding elements from two different lists. How can i use lamba expressions to perform the same steps above?

1
  • 1
    That code does nothing. list1 and list2 are empty Commented Mar 7, 2017 at 13:51

2 Answers 2

2

The following code does the same:

List<String> result = Stream.concat(
        list1.stream().flatMap(s -> Stream.of(s.getName(), s.getParentName())),
        list2.stream().flatMap(m -> Stream.of(m.getName(), m.getManagerName()))
        )
        .collect(Collectors.toList());

If you need to make sure that an ArrayList is created just use Collectors.toCollection(ArrayList::new) instead.

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

1 Comment

Thanks Benko, if i want to store parentName to another list. How we can do this on same code ?
1

I'm not quite sure, but is this what you're looking for?

list1.forEach(s -> {
    result.add(s.getName());
    result.add(s.getParentName());
});
list2.forEach(m -> {
    result.add(m.getName());
    result.add(m.getManagerName());
});

Comments

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.