I am dealing with Java 8 threads, and I am wondering if I can solve this problem in a fancy way.
What is my scenario: Suppose I have a list of parties, and inside each element I have member names. I want to iterate over the list and create a new one with names and which side they belong to.
My first approach:
@Test public void test(){ Party firstParties = new Party("firstParty",Lists.newArrayList("Member 1","Member 2","Member 3")); Party secondParty = new Party("secondParty",Lists.newArrayList("Member 4","Member 5","Member 6")); List<Party> listOfParties = Lists.newArrayList(); listOfParties.add(firstParty); listOfParties.add(secondParty); List<Elector> electors = new ArrayList<>(); listOfParties.stream().forEach(party -> party.getMembers().forEach(memberName -> electors.add(new Elector(memberName,party.name)) ) ); } class Party { List<String> members = Lists.newArrayList(); String name = ""; public Party(String name, List<String> members) { this.members = members; this.name = name; } public List<String> getMembers() { return members; } } class Elector{ public Elector(String electorName,String partyName) { } }
In my second approach, I tried using cards with flat cards:
@Test public void test(){ Party firstParty = new Party("firstParty",Lists.newArrayList("Member 1","Member 2","Member 3")); Party secondParty = new Party("secondParty",Lists.newArrayList("Member 4","Member 5","Member 6")); List<Party> listOfParties = Lists.newArrayList(); listOfParties.add(firstParty); listOfParties.add(secondParty); List<Elector> people = listOfParties.stream().map(party -> party.getMembers()) .flatMap(members -> members.stream()) .map(membersName -> new Elector(membersName, party.name)) #Here is my problem variable map doesn't exist .collect(Collectors.toList()); }
The problem is that I cannot access the member object inside the map operation. So again, the question is: can I make a more functional way? (like the second approach)
Thanks!
source share