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.
Related
This question already has answers here:
How to find an object in an ArrayList by property
(8 answers)
Checking if arraylist contains an object with an attribute [duplicate]
(4 answers)
How can I find one element of the object in an arraylist of objects? [duplicate]
(4 answers)
Closed 5 months ago.
I am new to Java. I have created an arraylist of objects of custom class. Objects of the class contain private variables like firstName, lastName, etc. and public getters and setters to access it and set it.
I wanted to loop through the arraylist to check if firstName in any of the objects in the indexes of arraylist matches the name entered by user. How do I check that?
I know that the get(i) method when used on arraylist returns the element in the specific index. But I don’t want the complete object. I want the variable inside the object.
You can use get(i) to get the whole object, and then append to that the getter of the attribute that you want. list.get(i).getLastName() for instance.
class Person {
private String firstName;
private String lastName;
public String getLastName() { return this.lastName; }
// ... etc ...
}
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("Jim", "Hawkins"));
list.add(new Person("Alexander", "Smollet"));
list.add(new Person("David", "Livesy"));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLastName().equals("Livesy")) { // <-----
System.out.println("Found matching name at index " + i);
}
}
}
This question already has answers here:
Java method: Finding object in array list given a known attribute value
(8 answers)
Closed 2 years ago.
I can't find a tutorial of this, every tutorial seems to use an ArrayList of strings.
Suppose you have a class Person which has many attributes including name.
class person
{
public String name;
public int age;
public int weight;
public String hair_colour;
public String eye_colour;
};
You have a ArrayList of persons and you want to find one person in this ArrayList and you only have their name.
ArrayList<person> people = new ArrayList<person>();
How do I find "Fred"?
I know it's possible to loop though all the items in list but I want to do this properly with an Iterator.
Does anyone know of a tutorial to explain how to do a find on an ArrayList using an Iterator to find an item using just one attribute of that item?
Or is this just not possible? Have I misunderstood Iterator's?
As pointed out in comments, iterator approach is very similar to what you do with standard loops:
public static Person findPersonByName(List<Person> list, String name) {
Iterator<Person> it = list.iterator();
while (it.hasNext()) {
Person p = it.next();
if (p.getName().equals(name)) { // Person found, return object
return p;
}
}
return null; // Not found return NULL
}
If you're using Java 8 and above, maybe you can try out streams(), they make this very compact:
public static Person findPersonByName(List<Person> list, String name) {
return list.stream().filter(p -> name.equals(p.getName())).findFirst().orElse(null);
}
This question already has answers here:
Sort List in reverse in order
(9 answers)
Closed 3 years ago.
I am new to the android studio. I want sort this ordersList in reverse order what should I do?
Collections.sort(ordersLists, new Comparator <OrdersList> () {
#Override
public int compare(OrdersList ordersList, OrdersList t1) {
return ordersList.getOrderID().compareToIgnoreCase(t1.getOrderID());
}
});
Use the comparator chain and reversed():
Collections.sort(
Comparator.comparing(OrderList::getOrderID, String.CASE_INSENSITIVE_ORDER)
.reversed());
You can do it by multiplying the result with -1 e.g.
Collections.sort(ordersLists, new Comparator <OrdersList> () {
#Override
public int compare(OrdersList ordersList, OrdersList t1) {
return ordersList.getOrderID().compareToIgnoreCase(t1.getOrderID()) * -1;
}
});
Just call .reversed() on your Comparator.
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.
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