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. You can use this method as long as your ArrayList is not immutable, I mean, not created using the Collections.unmodifiableList(), in such case the set() method throws java.lang.UnsupportedOperationExcepiton. Though you can also use the set() method with the List returned by Arrays.asList() method as oppose to add() and remove() which is not supported there. You just need to be careful with the index of elements. For example, if you want to replace the first element then you need to call set(0, newValue) because similar to an array, the ArrayList index is also zero-based. Now, the questions come why do you want to replace an element in the ArrayList? Why not just remove the element and insert a new one? Well, obviously the remove and insert will take more time than replace. The java.util.ArrayList provides O(1) time performance for replacement, similar to size(), isEmpty(), get(), iterator(), and listIterator() operations which runs in constant time. Now, you may wonder that why set() gives O(1) performance but add() gives O(n) performance, because it could trigger resizing of the array, which involves creating a new array and copying elements from the old array to the new array. You can also see these free Java courses to learn more about the implementation and working of ArrayList in Java. Here is an example of replacing an existing value from ArrayList in Java. In this example, I have an ArrayList of String which contains names of some of the most popular and useful books for Java programmers.Our example replaces the 2nd element of the ArrayList by calling the ArrayList.set(1, "Introduction to Algorithms") because the index of the array starts from zero. You should read a comprehensive course like The Complete Java Masterclass on Udemy to learn more about useful collection classes in Java, including ArrayList. import java.util.ArrayList;
import java.util.List; /* * Java Program to demonstrate how to replace existing value in * ArrayList. */ public class ArrayListSetDemo { public static void main(String[] args) { // let's create a list first List<String> top5Books = new ArrayList<String>(); top5Books.add("Clean Code"); top5Books.add("Clean Coder"); top5Books.add("Effective Java"); top5Books.add("Head First Java"); top5Books.add("Head First Design patterns"); // now, suppose you want to replace "Clean Coder" with // "Introduction to Algorithms" System.out.println("ArrayList before replace: " + top5Books); top5Books.set(1, "Introductoin to Algorithms"); System.out.println("ArrayList after replace: " + top5Books); } } Output
ArrayList before replace: [Clean Code, Clean Coder, Effective Java, Head First Java, Head First Design patterns]
ArrayList after replace: [Clean Code, Introduction to Algorithms,
Effective Java, Head First Java, Head First Design patterns]
That's all about how to replace existing elements of ArrayList in Java. The set() method is perfect to replace existing values just make sure that the List you are using is not immutable. You can also use this method with any other List type like LinkedList. The time complexity is O(n) because we are doing index-based access to the element. Other ArrayList tutorials for Java Programmers
private void myMethod () { LocalDateTime l = } origin: stackoverflow.com List<String> list = Arrays.asList( "one", "two", "three", null, "two", null, "five" ); System.out.println(list); // [one, two, three, null, two, null, five] Collections.replaceAll(list, "two", "one"); System.out.println(list); // [one, one, three, null, one, null, five] Collections.replaceAll(list, "five", null); System.out.println(list); // [one, one, three, null, one, null, null] Collections.replaceAll(list, null, "none"); System.out.println(list); // [one, one, three, none, one, none, none] static List<String> argsReplace(List<String> template, String parameter) { List<String> result = new ArrayList<>(template); Collections.replaceAll(result, "{}", parameter); return result; } } origin: apache/cloudstack @Override @ActionEvent(eventType = EventTypes.EVENT_FIREWALL_EGRESS_OPEN, eventDescription = "creating egress firewall rule for network", create = true) public FirewallRule createEgressFirewallRule(FirewallRule rule) throws NetworkRuleConflictException { Account caller = CallContext.current().getCallingAccount(); Network network = _networkDao.findById(rule.getNetworkId()); if (network.getGuestType() == Network.GuestType.Shared) { throw new InvalidParameterValueException("Egress firewall rules are not supported for " + network.getGuestType() + " networks"); } List<String> sourceCidrs = rule.getSourceCidrList(); if (sourceCidrs != null && !sourceCidrs.isEmpty()) Collections.replaceAll(sourceCidrs, "0.0.0.0/0", network.getCidr()); return createFirewallRule(null, caller, rule.getXid(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), sourceCidrs, rule.getDestinationCidrList(), rule.getIcmpCode(), rule.getIcmpType(), null, rule.getType(), rule.getNetworkId(), rule.getTrafficType(), rule.isDisplay()); } origin: stackoverflow.com List<String> list = Arrays.asList(new String[] {"a","b"}); System.out.println(list); Collections.replaceAll(list, "a", "!!!!!"); System.out.println(list); origin: stackoverflow.com String[] values= {null,"p", ";","z",null, "OR","y"}; List<String> list=new ArrayList<String>(Arrays.asList(values)); Collections.replaceAll(list, null, "newVal"); values = list.toArray(new String[list.size()]); System.out.println(Arrays.toString(values)); origin: stackoverflow.com List<String> lines = new ArrayList<String>(); lines.add("This"); lines.add("this"); lines.add("THIS"); lines.add("this won't work."); Collections.replaceAll(lines, "this", "****"); System.out.println(lines); origin: stackoverflow.com // let's say: // whole = "The city of San Francisco is truly beautiful!", // token = "San Francisco" public static String[] excludeString(String whole, String token) { // replaces token string "San Francisco" with "SanFrancisco" whole = whole.replaceAll(token, token.replaceAll("\\s+", "")); // splits whole string using space as delimiter, place tokens in a string array String[] strarr = whole.split("\\s+"); // brings "SanFrancisco" back to "San Francisco" in strarr Collections.replaceAll(Arrays.asList(strarr), token.replaceAll("\\s+", ""), token); // returns the array of strings return strarr; } origin: org.talend.components/components-salesforce-runtime public BulkResultSet getResultSet(InputStream input) throws IOException { CsvReader reader = new CsvReader(new InputStreamReader(input), getDelimitedChar(columnDelimiter)); List<String> baseFileHeader = null; if (reader.readRecord()) { baseFileHeader = Arrays.asList(reader.getValues()); Collections.replaceAll(baseFileHeader, "sf__Id", "salesforce_id"); Collections.replaceAll(baseFileHeader, "sf__Created", "salesforce_created"); } return new BulkResultSet(reader, baseFileHeader); } origin: Talend/components public BulkResultSet getResultSet(InputStream input) throws IOException { CsvReader reader = new CsvReader(new InputStreamReader(input), getDelimitedChar(columnDelimiter)); List<String> baseFileHeader = null; if (reader.readRecord()) { baseFileHeader = Arrays.asList(reader.getValues()); Collections.replaceAll(baseFileHeader, "sf__Id", "salesforce_id"); Collections.replaceAll(baseFileHeader, "sf__Created", "salesforce_created"); } return new BulkResultSet(reader, baseFileHeader); } origin: Qihoo360/Quicksql public static void collect(RexNode node, RexNode seek, Logic logic, List<Logic> logicList) { node.accept(new LogicVisitor(seek, logicList), logic); // Convert FALSE (which can only exist within LogicVisitor) to // UNKNOWN_AS_TRUE. Collections.replaceAll(logicList, Logic.FALSE, Logic.UNKNOWN_AS_TRUE); } origin: org.apache.calcite/calcite-core public static void collect(RexNode node, RexNode seek, Logic logic, List<Logic> logicList) { node.accept(new LogicVisitor(seek, logicList), logic); // Convert FALSE (which can only exist within LogicVisitor) to // UNKNOWN_AS_TRUE. Collections.replaceAll(logicList, Logic.FALSE, Logic.UNKNOWN_AS_TRUE); } origin: com.github.sommeri/less4j public void replaceSelector(Selector oldSelector, Selector newSelector) { oldSelector.setParent(null); newSelector.setParent(this); Collections.replaceAll(this.selectors, oldSelector, newSelector); } public static Geometry replace(Geometry parent, Geometry original, Geometry replacement) { List elem = extractElements(parent, false); Collections.replaceAll(elem, original, replacement); return parent.getFactory().buildGeometry(elem); } } |