Tuesday, August 20, 2024

Java: of list and set

There are multiple ways to construct a list in java. (easier in python and other languages). To eliminate duplicates, you can use the stream distinct, or put it in a set (HashSet or LinkedHashSet to retain order) then make it back to a list.
	public static void main(String arg[]) {
		
		String a[] = new String[] { "A", "B", "C", "D", "A", "C", "E" };
        List<String> list = Arrays.asList(a);  // constructed one way
        List<String> list2 = List.of(a); // constructed another way (java 9+)
        List<String> list3 = List.of( "A", "B", "C", "D", "A", "C", "E" ); // yet another way 

        // using stream distinct one way
        List<String> noDups = list.stream().distinct().collect(Collectors.toList());
        // using stream distinct another way
        List<String> noDups2 = list2.stream().distinct().toList();
        
        // put on a set and make a iist out of it
        Set<String> set = new LinkedHashSet<>(); 
        set.addAll(list3); 
        List<String> noDups3 = new ArrayList<>(set);
        
        System.out.println(noDups);
        System.out.println(noDups2);
        System.out.println(noDups3);
	}

No comments: