Why does my list not change with lambda? [duplicate] - java

This question already has answers here:
Remove objects from an ArrayList based on a given criteria
(10 answers)
Closed 5 years ago.
I have the following simple method:
public void exercise2(List<String> list) {
list.stream().filter(s -> s.length() % 2 == 0).collect(Collectors.toList());
}
And simple test, which does not complete successfully:
#Test
public void testExercise2() {
Lesson1 lesson1 = new Lesson1();
List<String> list = new ArrayList<>(Arrays.asList("alpha", "bravo", "charlie",
"delta", "echo", "foxtrot"));
List<String> inputList = new ArrayList<>(list);
lesson1.exercise2(list);
assertEquals("Input " + inputList.toString(), Arrays.asList("echo"), list);
}

Streams never modify the original list.
Your function creates a new list, then ignores it.

Related

How to add list [index] value to another list using method reference..? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
This is my list value [a,b,c,d] , I tried to add list[1] index value b to another list.. If am using lambda! am able to achieve this, any methods or ways was there to achieve same thing using method reference?.
Below code i tried
List<String> list1 = new ArrayList<>();
//list1 values are like [a,b,c,d]
List<String> list2 = new ArrayList<>();
list1.forEach(x-> {
list2.add(x.get(1));
});
How to achieve same thing using ::
list1.foreach(list1::add);
list1.forEach( x -> { } ) works like this: the operation between {} is done for every x from your list. This means that x is already an element and the x.get(1) will not provide the expected result.
One solution could be to simply use : list2.add(list1.get(1));
If you really want to use method reference and lambdas, you can use a BiConsumer functional interface. Here is an example:
BiConsumer<List<String>, String> addConsumer = List::add;
List<String> list1 = new ArrayList<>(); //values [a,b,c,d]
List<String> list2 = new ArrayList<>();
addConsumer.accept(list2, list1.get(1));
So if you think about the actual lambda, it is a Consumer<T> meaning that is can be reference by any method that takes a type of T and returns void. So in this example since you are looking for an something that uses a method reference I gave this. It isn't pretty but I want you to understand the point that List<T>.forEach((T t) -> {}) is just List<T>.forEach(Consumer<T>) || List<T>.forEach(<some method reference that takes type T as a single argument and returns void>)
Here is a simple example.
package org.stackoverflow.thread_safe_account;
import java.util.ArrayList;
import java.util.List;
public class Main {
private static List<String> knownList = new ArrayList<>();
public static void main(String[] args) {
//list1 values are like [a,b,c,d]
List<String> createdList = new ArrayList<>();
createdList.add("this");
createdList.add("is");
createdList.add("zoo");
createdList.add("stackoverflow");
createdList.forEach(Main::itemConsumer);
if (!knownList.get(0).equals("t")) {
throw new RuntimeException("failed");
}
if (!knownList.get(1).equals("i")) {
throw new RuntimeException("failed");
}
if (!knownList.get(2).equals("z")) {
throw new RuntimeException("failed");
}
if (!knownList.get(3).equals("s")) {
throw new RuntimeException("failed");
}
}
public static void itemConsumer(String item) {
if (item.length() < 1) knownList.add("");
else knownList.add(item.substring(0, 1));
}
}
indexOf() will return the index of the first occurrence of the object
List<Integer> list2 = new ArrayList<>();
list2.add(list1.indexOf("b"));

List Exception java.lang.UnsupportedOperationException [duplicate]

This question already has answers here:
Java List.add() UnsupportedOperationException
(8 answers)
UnsupportedOperationException when trying to remove from the list returned by Array.asList
(6 answers)
Arrays.asList give UnsupportedOperationException [duplicate]
(2 answers)
List.addAll throwing UnsupportedOperationException when trying to add another list [duplicate]
(5 answers)
Closed 3 years ago.
I keep getting java.lang.UnsupportedOperationException when trying to add a new item to the List e.g. Items.add(p); Could you help me in understanding why I am getting this exception?
import java.util.Arrays;
import java.util.List;
public class Item {
int id; int price;
public Item(int id, int price) {
this.id = id;
this.price = price;
}
#Override
public String toString() {
return id + ":" + price;
}
public static void main(String[] args) {
List<Item> Items = Arrays.asList(new Item(1, 30), new Item(2, 50), new Item(2, 40) );
Item p = Items.stream().reduce(new Item(4,0),(p1, p2) -> {
p1.price += p2.price;
return new Item(p1.id, p1.price);
});
System.out.println(p);
Items.add(p);
Items.stream().parallel().reduce((p1,p2) -> p1.price > p2.price?p1:p2).ifPresent(System.out::println);
}
}
Arrays.asList method returns an fixed sized list backed by provided array. You can not add or remove elements from it.
It returns an object of a special class (not ArrayList or LinkedList) which implement List interface. All size changing methods are implemented as to throw java.lang.UnsupportedOperationException.
If you want a List capable of adding further elements create an ArrayList and add your elements to it.

Nullpointerexception when I perform depth first search [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Suppose area1 has three contents 2,3,4, area2 has three contents 1,2,3 and area3 has two contents 1,2. m is the map that keys are locationid and values are list of contentid. For example, area1 has the map (1,{2,3,4}). Each area choose 1 content and find all the combination. I use dfs (recursion) to solve this problem but there is a nullpointerexception in line1. The intermediate is a list of string and i iterate through the list and their types are both string, why there is a null pointer exception? This is a specific condition in nullpointerexception and it is not duplicate.
public static List<String> dfs(String digits,Map<String, List<String>> m) {
List<String> result = new ArrayList<String>();
if(digits.length() == 0){
return result;
}
if(digits.length() == 1){
return m.get(digits.charAt(0));
}
List<String> intermediate = dfs(digits.substring(1, digits.length()),m);
for(String first : m.get(Character.toString(digits.charAt(0)))){
for(String rest : intermediate){ // line1
result.add(first + rest);
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String digits="123";
Map<String,List<String>> selected=new HashMap<>();
selected.put("1", new ArrayList<>(Arrays.asList("4","2","3")));
selected.put("2", new ArrayList<>(Arrays.asList("1","2","3")));
selected.put("3", new ArrayList<>(Arrays.asList("1","2")));
dfs(digits,selected);
}
I guess the problem is here:
return m.get(digits.charAt(0));
it should return null, since digits.charAt(0) is not a String
you need to use substring or Character.toString( here to extract the number

Add String Values from a for loop to list [duplicate]

This question already has answers here:
How to make a new List in Java
(25 answers)
Closed 7 years ago.
public static void printFiles(NodeList node) {
for (int i = 0; i < node.getLength(); i++) {
Node file = node.item(i);
String nodeValue = file.getAttributes().getNamedItem("urlName").getNodeValue();
System.out.println(nodeValue);
}
}
output:
0a4f171c-e0a4-4aa8-b43b-3989c235ff58.txt
0ccfa1a4-16b0-4e1f-abc9-e17907bb591f.txt
17c0545b-377e-4e0a-bb45-29f38fc91533.txt
3b341bf0-2cd7-46fe-a834-5b67804e5ff1.txt
48121209-d58e-4565-83b7-05062799be6e.txt
511b7a89-e4de-4f6e-9c8f-5ba65f675d7b.txt
compress.txt
dadadada.txt
e0c44cb9-2b1c-444c-a429-64531ea6a9a0.txt
e68b1d1d-9a66-4678-a6c1-76c64ae8be08.txt
hgafgahfka.txt
jdjajhdajdajd.txt
test1.txt
test2.txt
I parsed the xml document and got the values through for loop but those alues need to be in single place like List so that I can pass to some other function.can some one please let me know how to add those in a List .Below is the code and the current Output.
String input = "hello world";
List<String> list = new ArrayList<>();
list.add(input);
System.out.println(list.get(0));
> hello world
Good luck

how do you sort an array with different elements [duplicate]

This question already has answers here:
How to sort an array of objects in Java?
(11 answers)
Closed 8 years ago.
I have to sort the following array by the items name (the second element) how do I do this? I am stuck.
items[0] = new Product("001","Glue sticks",6,.06);
items[1] = new Product("002","Six inch rulers",25,.59);
items[2] = new Product("003","Paper-ream",5,6.99);
items[3] = new Product("004","Black ink pens",15,.97);
items[4] = new Product("005","No. 2 pencils",20,.30);
Use a Comparator
Arrays.sort(items, new Comparator<Product>()
{
#Override public int compare(final Product p1, Product p2)
{
// TODO check for null object
return p1.getName().compareTo(p2.getName());
}
});
maybe is better you use from arraylist and arraylist.sort() method

Categories