How to iterate through nested java collections using lambda [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I read through several threads about operating on the nested java collections using Lambda but none addressed my specific situation, although this one came close and then took off to a different direction (flatMap). Please show me how to write the following code in Lambda.
for(AppUser user : users){
List<CustomerOrder> orders = user.getOrders();
for(CustomerOrder order : orders){
order.setConsumer(user);
List<LineItem> items = order.getLineItems();
for (LineItem item : items){
item.setOrder(order);
}
}
}
Thanks

If all you want to do is iterate, the forEach method on either the Stream.java or the Iterable.java should be enough. Here is the "streamy" way of doing what you are trying to do with the for loops
users.stream().forEach( user ->
user.getOrders().stream().forEach( order -> {
order.setConsumer(user);
order.getLineItems().stream().forEach(
lineItem -> lineItem.setOrder(order)
);
}
));
Although you don't really need to convert the iterable returned by by those getters to streams.

This is a solution I came up with but I see that Smarth Ktyal already posted an answer.
users
.stream()
.forEach(e->e.getOrders()
.stream()
.forEach(k->{
k.setConsumer(e);
k.getLineItems()
.stream()
.forEach(l->l.setOrder(k));
}
)
);

Related

list.stream().collect(Collectors.toList()); returns empty list [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
choices is a List of two elements
but choices.stream().collect(Collectors.toList()); returns an empty list
Would anyone know why?
//returns poll with list of choices
public Poll accessPoll(String pollId) {
return pollRepository.findById(pollId).orElseThrow(
() -> new IllegalStateException(String.format("No poll found for the ID: %s.", upperCasePollId)));
}
List<Choice> choices = pollManager.accessPoll(pollId).getChoices(); //returns list of choices
List<Choice> choices1 = pollManager.accessPoll(pollId).getChoices()
.stream().collect(Collectors.toList()); //returns empty list
Look carefully at your screenshots. Your method getChoices() returns not a regular list but IndirectList which extends not a regular Collection but a Vector and that is why streams don't work as expected. This is a known bug in EclipseLink,
you can read about it more here and here.
To overcome this behaviour, you can try to update your EclipseLink version up to 2.6.0, or you may try to wrap it with a new collection, like new ArrayList<>()

Why stream() doesn't work from just declared Array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
It's probably sth simple, but I can't find answers why I can't start stream straight after creating List using Arrays.asList. 'list' is working fine, but 'list2' doesn't, no help from IntelliJ
List<Book> list = Arrays.asList(lalka,dziady,chlopi,jutrzenka);
list.stream()
.map((Book var)-> var.getAuthor().getName())
.forEach(var-> System.out.println(var));
List<Book> list2 = Arrays.asList(lalka, dziady).stream()
.map((Book var) -> var.getAuthor().getName())
.forEach(var-> System.out.println(var));
Your stream pipeline doesn't return anything (the terminal operation forEach has a void return type) so you can't assign it to a List variable.
You can write:
Arrays.asList(lalka, dziady)
.stream()
.map((Book var) -> var.getAuthor().getName())
.forEach(var-> System.out.println(var));
You're trying to assign result of .forEach to a List<Book> list2 variable.
.forEach(...) is of type void.
Remove this unnecessary assignment.
The problem is with the assignment to List list2.
You'll probably be getting an error that you cannot convert void to list
as .forEach() does not return anything.
Remove the assignment to list2 and this compiles and runs just fine.

Count number of occurrences in various lists Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I've got in Java a map of this type
Map<Group, List<Person>>
that is a set of groups with the whole list of members.
I want to find the Person that is in the largest number of groups using streams and lambda expressions, I tried something but it wasn't successful.
Can you help me please? Thanks
What you need is .flatMap() followed by a .collect() which finds the frequency of each person in the overall Map.
Something like this:
Person socialButterfly = groupMap.values()
.stream()
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.get().getKey();
Ideone Tested

How to filter a list for multiple condition using java 8 stream API? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This Code works fine in java 7.
Iteration in java 8 is successful but I am stacked while if else decision making.
I have one list in which i have integer as well as double value. How can i parse this and set to in model class?
AverageRatingModel avgRatingModel = new AverageRatingModel();
for(Property p:propertylist){
if(p.getName().equals("averagevote")){
avgRatingModel.setAvgRating(Double.parseDouble(p.getValue()));
}
if(p.getName().equals("nbvotes")){
avgRatingModel.setNoOfVotes(Integer.parseInt(p.getValue()));
}
}
You can use two streams but it would be horrible. It would must better to have a data structure which is designed for Properties.
properties.ifPresentDouble("averagevote", avgRatingModel::setAvgRating);
properties.ifPresentInt("nbvotes", avgRatingModel::setNoOfVotes);
You code will be much cleaner if you have useful data structure for your properteis.

How to create a Java program that removes duplicated words from text file? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to make a program in Java that could remove duplicated words in a text file. I'm a rookie in programming and I've been googling but I haven't found an understandable guideline to create such a program. I'm not asking for a completed program as an answer (although that is very desirable :p), but I'd really like some suggestions on how to develop this program. Please, anyone? I can manage programming, I just don't know what steps should be taken here.
Just for fun, I wrote a quick solution, which uses the Guava library heavily to avoid boilerplate IO code.
The key is LinkedHashMap, part of standard Java SDK, which is a Set (i.e. a duplicate-free collection) whose elements are kept in insersertion-order.
This approach is exactly what eis commented, with LinkedHashMap used as the "structure that doesn't allow duplicates".
private static void removeDuplicateWords(File file) {
try {
String contents = Files.toString(file, Charsets.UTF_8);
String[] words = contents.split("\\s+"); // or however you define "word"!
// UsingLinkedHashSet to remove duplicates while retaining order
LinkedHashSet<String> linkedHashSet = Sets.newLinkedHashSet();
Collections.addAll(linkedHashSet, words);
String newContents = Joiner.on(" ").join(linkedHashSet);
Files.write(newContents, file, Charsets.UTF_8);
} catch (IOException e) {
System.out.println(e);
}
}
Use String.split(" ") to get all the words in your text to array (String[]), then append them into a SET so no duplicats will appear. Now go with loop over the array to re-write the text and erase the matching word from the SET. add condition the if a word is in the araay but not in the SET (means that it's duplicate) It will not be re-write
hopes it helps

Categories