I'm somewhat new to working in Java 8, and am refactoring some older code with (what appears to be a good use case for) a stream operation. The older code "works" but to my eyes it looks really inefficient.
The short version of my question is that I'm trying to find a single element of a List and replace it with an updated version of that same element (the key is the same, but properties have different values each time the code is called).
try
{
List<Object> items = lookup(itemCache.getKey());
for (int i = 0; i < items.size(); i++)
{
Object originalObject = items.get(i);
if (originalObject.getPropValue() == newObject.getPropValue())
{
List<Object> newItems = new ArrayList<>(items);
newItems.set(i, newObject);
putIntoCache(newObject.getKey(), newItems);
break;
}
}
}
catch (Exception ex) { /*exception handling*/ }
Based on what I've read about streams thus far, it seems that I need to use a .map()
or .filter()
to isolate the element I want to identify, but that also seems like operations occurring after either filter
or map
in the stream statement would be operating on either not the full List or on a List where every item is affected by the .map()
.
It seems simple, but I am struggling to wrap my head around it. Because the initial lookup is a List
itself, I was thinking the stream could replace all of this. The ArrayList<>()
appears in the original code, but ordering of the items isn't important so long as I am able to replace that item by its key.
If you choose to help, thank you.
You can use the set() method of java. util. ArrayList class to replace an existing element of ArrayList in Java. The set(int index, E element) method takes two parameters, the first is the index of an element you want to replace, and the second is the new value you want to insert.
Using Streams, we can apply lambda functions known as Predicates. To read more about Streams and Predicates, we have another article here. Internally, removeIf uses an Iterator to iterate over the list and match the elements using the predicate. We can now remove any matching elements from the list.
To replace an element in Java ArrayList, set() method of java. util. An ArrayList class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element.
To update or set an element or object at a given index of Java ArrayList, use ArrayList. set() method. ArrayList. set(index, element) method updates the element of ArrayList at specified index with given element.
You can simply do:
List<Object> newItems = items.stream()
.map(o -> o.getPropValue() == newObject.getPropValue() ? newObject : o)
.collect(toList());
putIntoCache(newObject.getKey(), newItems);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With