If you wanna create new list, use Stream.map method:
List<Fruit> newList = fruits.stream()
.map(f -> new Fruit(f.getId(), f.getName() + "s", f.getCountry()))
.collect(Collectors.toList())
If you wanna modify current list, use Collection.forEach:
fruits.forEach(f -> f.setName(f.getName() + "s"))
Answer from Sergii Lagutin on Stack OverflowIf you wanna create new list, use Stream.map method:
List<Fruit> newList = fruits.stream()
.map(f -> new Fruit(f.getId(), f.getName() + "s", f.getCountry()))
.collect(Collectors.toList())
If you wanna modify current list, use Collection.forEach:
fruits.forEach(f -> f.setName(f.getName() + "s"))
You can use just forEach. No stream at all:
fruits.forEach(fruit -> fruit.setName(fruit.getName() + "s"));
You can do this:
myList.get(3).setEmail("new email");
Fixed. I was wrong: this only applies on element reassignment. I thought that the returned object wasn't referencing the new one.
It can be done.
Q: Why?
A: The get() method returns an object referencing the original one.
So, if you writemyArrayList.get(15).itsVariable = 7
or
myArrayList.get(15).myMethod("My Value"),
you are actually assigning a value / using a method from the object referenced by the returned one (this means, the change is applied to the original object)
The only thing you can't do is myArrayList.get(15) = myNewElement. To do this you have to use list.set() method.
You should have a block after your condition :
if (searchID.equals(S1.getID())) {
System.out.print("\n\tEnter New Data: ");
S1.setting();
}
Otherwise, you'll always call S1.setting(), regardless of the result of the condtion, since without the curly braces, the if statement only controls whether or not System.out.print("\n\tEnter New Data: "); will be executed.
I've put it through my code cleaner and below is what it shows like:
if (studentList.isEmpty()) {
System.out.println("\t\tNO DATA TO UPDATE !!");
} else {
try {
System.out.print("\n\tTo Update info, Please Enter Students ID: ");
System.out.flush();
searchID = obj.readLine();
for (final Iterator<Student> it = studentList.iterator(); it.hasNext();) {
final Student S1 = it.next();
if (searchID.equals(S1.getID())) {
System.out.print("\n\tEnter New Data: ");
S1.setting();
}
// >>> this is where S1.setting() went wrong, moved up <<<
}
} catch (final Exception e) {
// empty
}
}
The most important change is that all code blocks are with braces {}. If you do this it becomes very clear when a statement is executed. Without that only the first statement behind an if or else clause is executed. This makes it very easy to make coding mistakes as the one in the question.
ArrayList.set(int index, Object element). This method ask you the destination index as first parameter and the new element as second parameter. You are trying to set arr.get(i) to the arr.get(i+1) position. I think you're trying to set it to the position i+1 instead:
for (i = arr.size()-2; (i >=0) && ( arr.get(i)>sort); i--) {
arr.set(i+1, arr.get(i));
System.out.println(arr);
}
The issue is with set(int index, E element)
Assume this is your array : [1, 2, 3, 4, 5, 6]
At the first iteration:
int val = arr.get(i); //Val = 5 int index = arr.get(i+1); //index = 6
The error is here: arr.set (index, val) . As you see the "index" is more than the list size, due to which it is causing the issue.
Below peace of code avoids this issue:
for (int i = arr.size()-2 ; (i >=0) && (arr.get(i) > sort) ; i--){
arr.set(arr.get(i), arr.get(i));
System.out.println(arr);
}
No new object was created. You've updated the object in the list, that is, the object in the list will have "New name here" as name.
In fact this you could test and see with a debugger.
No New Object is Created, you are modifying the existing value.
In fact this is not a good practice,you should allow access to your class variables directly, make them as private and provide setter/getter methods for the same.
public class Profile {
private String name, age, location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
If you know the position of the element do only the following:
userList.get(index).setUsername("newvalue");
If not, you need to loop all the elements to find the element to update
for (User user : userList) {
if (user.getUserId().equals(searchedId)) {
user.setUsername("newvalue");
break;
}
}
In your case I think it's better using a Map instead of a List:
Map<Integer, User> userMap = new HashMap<Integer, User>();
User user = new User();
user.setUserId(1);
user.setUsername("user1");
userMap.put(user.getUserId(), user);
user = new User();
user.setUserId(2);
user.setUsername("user2");
userMap.put(user.getUserId(), user);
user = new User();
user.setUserId(3);
user.setUsername("user3");
userMap.put(user.getUserId(), user);
In this way, you can search directly for the userId you need:
User userToModify = userMap.remove(idToModify);
userToModify.setUsername("new name");
userToModify.setUserId(54);
userMap.put(user.getUserId(), userToModify);
If you need to find object only by one field (userId, in this case), a Map is far more efficient and easy to use (and to maintain).
You don't have to insert a new item to ArrayList
public void modify(String name) {
for (Item i : item) {
if (i.getName().equalsIgnoreCase(name)) {
System.out.println("New name: ");
String newName = in.nextLine();
i.setName(newName);
}
}
}
It's supposed you have set methods for each field. Then you can update name, price, size this way
You can have an updateName method in the Item class, and then only update the object's name:
item.get(index).updateName(newName);
item.get(index) returns an Item object, on which you apply the updateName method.
Use the set method to replace the old value with a new one.
list.set( 2, "New" );
If you are unaware of the position to replace, use list iterator to find and replace element ListIterator.set(E e)
ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next.equals("Two")) {
//Replace element
iterator.set("New");
}
}