{
"code1":{"id":"11","name":"n11"},
"code2":{"id":"12","name":"n12"}
}
Map<String, SaleSkuVO> skuByItemNoMap = skus.stream().collect(Collectors.toMap(SaleSkuVO::getItemNo, p -> p, (o, n) -> o));
Map<String, List<SaleSkuVO>> skuByItemNoMapList = skus.stream().collect(Collectors.groupingBy(SaleSkuVO::getItemNo));
{
"code1":[
{"id":"11","name":"n11","code":"code1"},
{"id":"21","name":"n21","code":"code1"}
],
"code2":[
{"id":"12","name":"n12","code":"code2"},
{"id":"22","name":"n22","code":"code2"}
]
}
// 根据id去重
List<Person> unique =
appleList.stream().collect(
collectingAndThen(
toCollection( () -> new TreeSet<>(comparingLong(Apple::getId)) ),
ArrayList::new
)
);
https://zacard.net/2016/03/17/java8-list-to-map/
重复key的情况
代码如下:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity()));
}
这个方法可能报错(java.lang.IllegalStateException: Duplicate key),因为name是有可能重复的。toMap有个重载方法,可以传入一个合并的函数来解决key冲突问题:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}
这里只是简单的使用后者覆盖前者来解决key重复问题。
指定具体收集的map
toMap还有另一个重载方法,可以指定一个Map的具体实现,来收集数据:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
}
TreeMap<String, List<User>> treeMap = userList.stream()
.sorted((o1, o2) -> o1.getAge() - o2.getAge())
.collect(groupingBy(item -> item.getHeight, TreeMap::new, toList()));
// lambda优雅取出对象list中某个属性重复的集合数据:
public class Test { // https://blog.csdn.net/qq_35902833/article/details/88351470
@Data
@AllArgsConstructor
static class Dog {
String name;
int age;
}
public static List<Dog> dogs = null;
static {
dogs = new ArrayList<Dog>() {
{
add(new Dog("黄一", 11));
add(new Dog("黄一", 22));
add(new Dog("黄三", 33));
}
};
}
//@SuppressWarnings("AlibabaAvoidManuallyCreateThread")
public static void main(String[] args) {
// dogs.stream()
// .flatMap(i->i.getSonList().stream()) // lambda: list1.addAll(list2)
// .collect(Collectors.toSet());
Map<String, Long> collect = dogs.stream().
collect(Collectors.groupingBy(i -> i.getName(), Collectors.counting()));
System.out.println("-1-->" + collect.toString()); //-1-->{黄三=1, 黄一=2}
Map<String, List<Dog>> collect1 = dogs.stream()
.collect(Collectors.groupingBy(Dog::getName));
System.out.println("-2-->" + collect1.toString());//-2-->{黄三=[test.Dog(name=黄三, age=33)], 黄一=[test.Dog(name=黄一, age=11), test.Dog(name=黄一, age=22)]}
IntSummaryStatistics summaryStatistics3 = dogs.stream().collect(Collectors.summarizingInt(Dog::getAge));
System.out.println("-3-->" + summaryStatistics3.getSum());//-3-->66
Map<String, IntSummaryStatistics> intSummaryStatistics = dogs.stream().
collect(Collectors.groupingBy(i -> i.getName(), Collectors.summarizingInt(Dog::getAge)));
System.out.println("-4-->" + intSummaryStatistics);
//-4-->{黄三=IntSummaryStatistics{count=1, sum=33, min=33, average=33.000000, max=33}, 黄一=IntSummaryStatistics{count=2, sum=33, min=11, average=16.500000, max=22}}
System.out.println("-5-->" + intSummaryStatistics.get("黄一").getSum()); //-5-->33
IntSummaryStatistics collect21 = dogs.stream().collect(Collectors.summarizingInt(Dog::getAge));
Optional.ofNullable(collect21).ifPresent(System.out::println); //IntSummaryStatistics{count=3, sum=66, min=11, average=22.000000, max=33}
System.out.println("-6-->" + Optional.ofNullable(collect21).get().getSum()); //-6-->66
List<String> collect7 = dogs.stream().
collect(Collectors.groupingBy(i -> i.getName(), Collectors.counting()))
.entrySet()
.stream()
.map(entry -> {
return "key-->" + entry.getKey() + "; val-->" + entry.getValue();
})
.collect(Collectors.toList());
System.out.println("-7-->" + collect7); //-7-->[key-->黄三; val-->1, key-->黄一; val-->2]
List<String> collect8 = dogs.stream().
collect(Collectors.groupingBy(i -> i.getName(), Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.map(entry -> entry.getKey())
.collect(Collectors.toList());
System.out.println("-7-->" + collect8); //-7-->[黄一]
Consumer<Dog> consumer = (dog) -> System.out.println("-8-->" + dog.getAge());
Predicate<Dog> dogPredicate = (dog) -> dog.getAge() > 10;
Test.dogs.stream()
.filter(dogPredicate)
.limit(3)
.forEach(consumer);
//-8-->11
//-8-->22
//-8-->33
}
}
// LIST、MAP、数组互转、分组Collectors.groupingBy
public class CollectionMy {
//出处:https://www.iteye.com/blog/bugyun-2433872
public static void main(String[] args) {
List<Person> listEntiyJapan = new ArrayList();
listEntiyJapan.add(new Person(1, "ha1", 10));
listEntiyJapan.add(new Person(2, "ha2", 11));
listEntiyJapan.add(new Person(2, "ha3", 12));
// String[] arrays = {"hello"," , ","world"};
//
// System.out.println(arrayToList1(arrays));
// System.out.println(arrayToList2(arrays));
// System.out.println(listToArray1(arrayToList2(arrays)));
// System.out.println(listToArray2(arrayToList2(arrays)));
//
// listToMap1(listEntiyChina);
// sortList(listEntiyJapan);
//
listToMap4(listEntiyJapan);
Map<String, Integer> mapRepeat = new HashMap<>();
}
//--------------进阶-List转为Map---------------------------------
/**
* Java8 List转为Map
* ID 必须为唯一性
*
* @param list
* @return
*/
public static void listToMap1(List<Person> list) {
// list<bean> -> Map<String, String>
//使用toMap方法的另一个变体来处理重复问题,它允许我们指定一个合并方法。这个合并方法允许用户他们指定想如何处理多个值关联到同一个键的冲突。
//在下面展示的代码中,我们只是使用了新的值,当然你也可以编写一个智能的算法来处理冲突。
Map<Integer, Person> mapp = list.stream().collect(Collectors.toMap(Person::getId, p -> p, (oldValue, newValue) -> newValue));
// Map<Integer, Person> mapp = list.stream().collect(Collectors.toMap(Person::getId, Function.identity(),(oldValue, newValue) -> newValue));
System.out.println("-10-->" + mapp);//-10-->{1=Person(id=1, name=ha1), 2=Person(id=2, name=ha2), 3=Person(id=3, name=ha3)}
//可以通过使用toMap方法的第三个变体来指定其他的映射实现。这需要你指定将用来存储结果的Map和Supplier。
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName, (oldValue, newValue) -> newValue, LinkedHashMap::new));
Map<Integer, String> map01 = list.stream().collect(Collectors.toMap(item -> item.getId(), item -> item.getName(), (oldVal, currVal) -> oldVal + "-" + currVal));
System.out.println("-11-->" + map); //-12-->{1=ha1, 2=ha2, 3=ha3}
System.out.println("-12-->" + map01.toString()); //-13-->{1=ha1, 2=ha2, 3=ha3-ha3}
}
/**
* 分组
* Java8 List转为Map Person -> Map<Integer, List<Person>>
* 根据年龄排序后,再根据ID重复分组
*
* @param list
* @return
*/
public static Map<Integer, List<Person>> listToMap4(List<Person> list) {
Collections.sort(list, Comparator.comparing(Person::getId).thenComparing(Person::getAge));
list.forEach(System.out::println);
Map<Integer, List<Person>> result = list.stream().collect(Collectors.groupingBy(Person::getId));
System.out.println("--4---->" + result);
//分组 演示
// Map<Person, Long> collect41 = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map<Person, Long> collect41 = list.stream().collect(Collectors.groupingBy(p -> p, Collectors.counting()));
System.out.println("--41---->" + collect41);
//1.3根据分组的key值对结果进行排序、放进另一个map中并输出
Map<Integer, Long> result1 = list.stream().collect(Collectors.groupingBy(Person::getId, Collectors.counting()));
System.out.println("--42---->" + result1);// {1=1, 2=2}
Map<String, Long> xMap = new HashMap<>();
result1.entrySet().stream().sorted(Map.Entry.<Integer, Long>comparingByKey().reversed()) //reversed不生效
.forEachOrdered(x -> xMap.put(x.getKey() + "", x.getValue()));
System.out.println("--43---->" + xMap);// {1=1, 2=2}
Map<Integer, Integer> result3 = list.stream().collect(
Collectors.groupingBy(Person::getId, Collectors.summingInt(Person::getAge))
);
System.out.println("--44---->" + result3);//{1=10, 2=23}
// 根据id去重 https://blog.csdn.net/lu930124/article/details/77595585/
List<Person> unique = list.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<Person>(comparingLong(Person::getId))), ArrayList::new
)
);
System.out.println("--45---->" + unique);//--45---->[Person(id=1, name=ha1, age=10), Person(id=2, name=ha2, age=11)]
return result;
}
//----------------------------------基础操作--------------
/**
* Java8 数组转为List
*
* @param arrays
* @return
*/
public static List<String> arrayToList1(String[] arrays) {
List<String> result = Stream.of(arrays).collect(Collectors.toList());
return result;
}
/**
* Java8 List转为数组
*
* @param list
* @return
*/
public static String[] listToArray1(List<String> list) {
String[] result = list.stream().toArray(String[]::new);
Arrays.stream(result).forEach(str -> System.err.println(str));
return result;
}
public static void sortList(List<Person> list) {
Collections.sort(list, Comparator.comparing(Person::getId).thenComparing(Person::getAge));
list.forEach(System.out::println);
}
public static List<String> arrayToList2(String[] arrays) {
List<String> result = Arrays.asList(arrays);
return result;
}
public static String[] listToArray2(List<String> list) {
String[] result = list.toArray(new String[list.size()]);
return result;
}
}
Set<String> skusByItemNoSet = skus.stream().map(SaleSkuVO::getItemNo).collect(Collectors.toSet());